An example of a Flask application. In a previous post I described a command line tool I have made to simplify and speed up the process of creating Flask based web applications. The post contained some screenshots showing how the starting application looked like and a link to the live website deployed on my server. If you visit the website you will see a Boostrap based page but nothing more so not much of a showcase for the tool.
An example of a Flask application done with the Flask command line tool
Opté por usar iccode.net para publicar un manual que describe cómo crear una aplicación simple basada en Flask. Esta constará de una o dos vistas (controladores), al menos un formulario, un modelo y uno o dos modelos, con el fin de alojarla en mi servidor y guardar una versión en git para referencia futura. Un análisis más detallado de los procedimientos mencionados en este tutorial, incluyendo aspectos técnicos, como el uso del componente de línea de comandos, la estructura de los archivos y el código generado, se puede encontrar aquí. Crear una aplicación demostrativa como esta debería ser suficiente para demostrar cómo funciona la herramienta.
For the tl;dr guys
Create this Flask project using this command line tool with 6 lines in terminal, ~10 lines of code and ~15 lines of HTML text and editing in about 10 minutes, that’s it!
Without further ado here are the required steps to create a database application with Flask – SQLAlchemy and WTForms using the Flask command line tool. Note you will find reference links at the bottom of the post, additionally in order to be able to follow-up with the example you will have to get the tool from here. The instructions on how to set a working environment are mentioned in project’s wiki. The example project will be named vote and will be about a voting application where the site visitor will be able to upvote or downvote our application.
The steps
The steps are divided in two parts, the first part describes the commands typed in terminal to invoke the Flask command line tool in order to auto generate most of the work. The second part is about the manual editing of the produced content in order to enrich and tweak application’s code and content.
1. Create a new Flask project named vote using jQuery & Bootstrap. The tool will create a directory structure for our newly created project, download jQuery and Bootstrap libraries and register them in the base template. Finally it will generate the first blueprint and various useful files containing settings, Python, CSS, JavaScript and HTML boilerplate code. Note that for each generated blueprint a set of files and directories are being generated. The most notable among them are the blueprint’s directory containing a views.py, models.py, forms.py, helpers.py and an __init__.py files. Additionally for each blueprint a new directory is generated in app/templates/ to host the templates of the blueprint.
1
|
$flask new vote jquery bootstrap
|
Command details: flask is the name of the command line tool, new is the command that generates a new project vote is the name of the project, jquery and bootstrap tell the tool that we want to use jQuery and Bootstrap in our project.
2. Our application will have one model named Voteresult with one field named result to hold a negative or a positive vote. Here is how to create the model.
1
|
$flask generate model VoteResult main result:integer
|
Command details: generate model is the command that generates the model, VoteResult is the name of the model, main tells the tool that the model belongs to the main blueprint which is auto generated at project’s creation, result:integer tell the tool that the model will have one field named result of type integer.
3. We will create one form named vote containing two buttons, one for the positive vote and one for the negative vote.
1
|
$flask generate form vote main positive:submit negative:submit
|
Command details: generate form is the command that generates the form, vote is the name of the form, main again tells the tools that the form belongs to the main blueprint, positive:submit and negative:submit are both form controls of type submit. Along with the auto generated form code, the tool also creates a template named vote (as the form’s name) to render the form.
4. We will create one template named results to show the voting results to our site’s visitors.
1
|
$flask generate template results main base
|
Command details: generate template is the command that generates the template, results is the name of the template, main tells the tool that the template belongs to the main blueprint, base tells the tool that the template will extend the base.html template so it will inherit the layout of our application.
5. In the final step we will create two views (controllers) to contain the logic of our application.
1
2
|
$flask generate view vote main template:vote route:vote method:get/post
$flask generate view results main template:results route:results method:get
|
Command details: generate view is the command that generates the view, vote is the view’s name, main tells the tool that the view belongs to the main blueprint, template:vote is the template the view will render, route:vote is the view’s routing url, method:get/post is the view’s HTTP methods. As with the first generated view, the second view follows the same concept, except the HTTP method.
After six tiresome entries in the terminal our example application is almost ready to be deployed. The only work left is to tweak the generated model, instantiate the form in the vote view and pass it to the template, add the voting logic and save each vote to the database; accordingly in the results view we will load the results and pass them to the results template. Finally we will write some text not lorem ipsum to introduce the application to the potential visitor. I will not include all the work as you can see it live or check out the final example application which is more or less the same.
1. In the produced model I have set the result field default value to be 0 and changed it’s unique attribute to false. Bellow is the relevant code part:
1
2
3
4
5
6
7
8
|
class Voteresult(db.Model):
__tablename__ = “voteresult”
voteresult_id = db.Column(db.Integer, primary_key=True)
result = db.Column(db.Integer, unique=False)
def __init__(self, result=None, ):
self.result = 0
|
2. The two views are posted in their final form (note that the imports are left out). Additionally you can see that no exception prediction is made, the example is just to showcase the command line tool not good code writing. The results view queries the database and counts the positive and negative votes and passes them to the results template. The vote view instantiates the vote form, if the request method is POST checks which button was pressed and stores the respective result to the database, finally renders the redirects to the results page. If the request method is GET the view renders the vote template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#———————————————————————-
@mod.route(“/results/”, methods=[“GET”])
def results():
votes = VoteresultModel.query.all()
s_votes = 0
p_votes = 0
n_votes = 0
for vote in votes:
if vote.result == 1:
p_votes += 1
elif vote.result == –1:
n_votes += 1
s_votes = p_votes + n_votes
app.logger.debug(s_votes)
app.logger.debug(“rendering template: main/results.html”)
return render_template(“main/results.html”, **locals())
#———————————————————————-
@mod.route(“/vote/”, methods=[“GET”, “POST”])
def vote():
form = VoteForm()
if request.method == “POST”:
if “possitive” in request.form:
vote_result = VoteresultModel()
vote_result.result = 1
db.session.add(vote_result)
db.session.commit()
elif “negative” in request.form:
vote_result = VoteresultModel()
vote_result.result = –1
db.session.add(vote_result)
db.session.commit()
app.logger.debug(“rendering template: main/results.html”)
return redirect(url_for(“main.results”))
else:
app.logger.debug(“rendering template: main/vote.html”)
return render_template(“main/vote.html”, form=form)
|
3. In the visual part the changes are simple HTML editing so not of much interest. The main changes worth mentioning are the removal of the initial text in the main page which involves the deletion of one {{ include “info.html” }} tag and the removal of the initial submit button in the vote template which is auto generated by the tool.
Please help us spread this information to as many people as possible. All you have to do is click on one of the buttons above. We thank you in advance for your great help.
Thanks for sharing