Flask Tutorial
Flask Tutorial
Audience
This tutorial has been prepared for anyone who has a basic knowledge of Python and has
an urge to develop websites. After completing this tutorial, you will find yourself at a
moderate level of expertise in developing websites using Flask.
Prerequisites
Before you start proceeding with this tutorial, we are assuming that you have hands-on
experience on HTML and Python. If you are not well aware of these concepts, then we will
suggest you to go through our short tutorials on HTML and Python.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Flask
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
2. Flask Environment.................................................................................................................................. 2
8. Flask Templates.................................................................................................................................... 13
ii
Flask
iii
1. Flask Overview Flask
What is Flask?
Flask is a web application framework written in Python. It is developed by Armin
Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is
based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.
WSGI
Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web
application development. WSGI is a specification for a universal interface between the web
server and the web applications.
Werkzeug
It is a WSGI toolkit, which implements requests, response objects, and other utility
functions. This enables building a web framework on top of it. The Flask framework uses
Werkzeug as one of its bases.
Jinga2
Jinga2 is a popular templating engine for Python. A web templating system combines a
template with a certain data source to render dynamic web pages.
Flask is often referred to as a micro framework. It aims to keep the core of an application
simple yet extensible. Flask does not have built-in abstraction layer for database handling,
nor does it have form a validation support. Instead, Flask supports the extensions to add
such functionality to the application. Some of the popular Flask extensions are discussed
later in the tutorial.
1
2. Flask Environment Flask
Prerequisite
Python 2.6 or higher is usually required for installation of Flask. Although Flask and its
dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do
not support it properly. Hence, it is recommended that Flask should be installed on Python
2.7.
This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If
you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using
its package manager.
mkdir newproj
cd newproj
virtualenv venv
venv/bin/activate
venv\scripts\activate
The above command can be run directly, without virtual environment for system-wide
installation.
2
3. Flask Application Flask
In order to test Flask installation, type the following code in the editor as Hello.py
@app.route('/')
def hello_world():
return 'Hello World
if __name__ == '__main__':
app.run()
Importing flask module in the project is mandatory. An object of Flask class is our WSGI
application.
The route() function of the Flask class is a decorator, which tells the application which
URL should call the associated function.
app.route(rule, options)
In the above example, / URL is bound with hello_world() function. Hence, when the
home page of web server is opened in browser, the output of this function will be rendered.
Finally the run() method of Flask class runs the application on the local development
server.
Python Hello.py
3
Flask
Open the above URL (localhost:5000) in the browser. Hello World message will be
displayed on it.
Debug mode
A Flask application is started by calling the run() method. However, while the application
is under development, it should be restarted manually for each change in the code. To
avoid this inconvenience, enable debug support. The server will then reload itself if the
code changes. It will also provide a useful debugger to track the errors if any, in the
application.
The Debug mode is enabled by setting the debug property of the application object to
True before running or passing the debug parameter to the run() method.
app.debug=True
app.run()
app.run(debug=True)
4
4. Flask Routing Flask
Modern web frameworks use the routing technique to help a user remember application
URLs. It is useful to access the desired page directly without having to navigate from the
home page.
The route() decorator in Flask is used to bind URL to a function. For example:
@app.route(/hello)
def hello_world():
return hello world
Here, URL /hello rule is bound to the hello_world() function. As a result, if a user visits
http://localhost:5000/hello URL, the output of the hello_world() function will be
rendered in the browser.
The add_url_rule() function of an application object is also available to bind a URL with
a function as in the above example, route() is used.
def hello_world():
return hello world
app.add_url_rule(/, hello, hello)
5
5. Flask Variable Rules Flask
It is possible to build a URL dynamically, by adding variable parts to the rule parameter.
This variable part is marked as <variable-name>. It is passed as a keyword argument
to the function with which the rule is associated.
In the following example, the rule parameter of route() decorator contains <name>
variable part attached to URL /hello. Hence, if the
http://localhost:5000/hello/TutorialsPoint is entered as a URL in the browser,
TutorialPoint will be supplied to hello() function as argument.
Save the above script as hello.py and run it from Python shell. Next, open the browser
and enter URL http://localhost:5000/hello/TutorialsPoint.
Hello TutorialsPoint!
In addition to the default string variable part, rules can be constructed using the following
converters:
6
Flask
@app.route('/rev/<float:revNo>')
def revision(revNo):
return 'Revision Number %f' % revNo
if __name__ == '__main__':
app.run()
Run the above code from Python Shell. Visit the URL http://localhost:5000/blog/11 in the
browser.
The given number is used as argument to the show_blog() function. The browser
displays the following output:
Blog Number 11
Enter this URL in the browser: http://localhost:5000/rev/1.1
The revision() function takes up the floating point number as argument. The following
result appears in the browser window:
Both the rules appear similar but in the second rule, trailing slash (/) is used. As a result,
it becomes a canonical URL. Hence, using /python or /python/ returns the same output.
However, in case of the first rule, /flask/ URL results in 404 Not Found page.
7
6. Flask URL Building Flask
The url_for() function is very useful for dynamically building a URL for a specific function.
The function accepts the name of a function as first argument, and one or more keyword
arguments, each corresponding to the variable part of URL.
The above script has a function user(name) which accepts a value to its argument from
the URL.
The User() function checks if an argument received matches admin or not. If it matches,
the application is redirected to the hello_admin() function using url_for(), otherwise to
the hello_guest() function passing the received argument as guest parameter to it.
http://localhost:5000/hello/admin
Hello Admin
8
Flask
http://localhost:5000/hello/mvl
9
7. Flask HTTP methods Flask
Http protocol is the foundation of data communication in world wide web. Different
methods of data retrieval from specified URL are defined in this protocol.
GET Sends data in unencrypted form to the server. Most common method.
Used to send HTML form data to server. Data received by POST method
POST
is not cached by server.
By default, the Flask route responds to the GET requests. However, this preference can
be altered by providing methods argument to route() decorator.
In order to demonstrate the use of POST method in URL routing, first let us create an
HTML form and use the POST method to send form data to a URL.
<html>
<body>
<form action="http://localhost:5000/login" method="post">
<p>Enter Name:</p>
<p><input type="text" name="nm" /></p>
<p><input type="submit" value="submit" /></p>
</form>
</body>
</html>
10
Flask
After the development server starts running, open login.html in the browser, enter name
in the text field and click Submit.
http://localhost/login is mapped to the login() function. Since the server has received
data by POST method, value of nm parameter obtained from the form data is obtained
by:
user=request.form['nm']
It is passed to /success URL as variable part. The browser displays a welcome message
in the window.
11
Flask
Change the method parameter to GET in login.html and open it again in the browser.
The data received on server is by the GET method. The value of nm parameter is now
obtained by:
User=request.args.get(nm)
Here, args is dictionary object containing a list of pairs of form parameter and its
corresponding value. The value corresponding to nm parameter is passed on to /success
URL as before.
12
8. Flask Templates Flask
It is possible to return the output of a function bound to a certain URL in the form of HTML.
For instance, in the following script, hello() function will render Hello World with <h1>
tag attached to it.
However, generating HTML content from Python code is cumbersome, especially when
variable data and Python language elements like conditionals or loops need to be put. This
would require frequent escaping from HTML.
This is where one can take advantage of Jinja2 template engine, on which Flask is based.
Instead of returning hardcode HTML from the function, a HTML file can be rendered by the
render_template() function.
Flask will try to find the HTML file in the templates folder, in the same folder in which this
script is present.
Application folder
o Hello.py
o templates
hello.html
The term web templating system refers to designing an HTML script in which the
variable data can be inserted dynamically. A web template system comprises of a template
engine, some kind of data source and a template processor.
13
Flask
Flask uses jinga2 template engine. A web template contains HTML syntax interspersed
placeholders for variables and expressions (in these case Python expressions) which are
replaced values when the template is rendered.
<!doctype html>
<html>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
As the development server starts running, open the browser and enter URL as:
http://localhost:5000/hello/mvl
14
Flask
The Jinga2 template engine uses the following delimiters for escaping from HTML.
<!doctype html>
<html>
<body>
{% if marks>50 %}
<h1> Your result is pass!</h1>
{% else %}
<h1>Your result is fail</h1>
{% endif %}
</body>
</html>
Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}.
Run the Python script and visit URL http://localhost/hello/60 and then
http://localhost/hello/30 to see the output of HTML changing conditionally.
The Python loop constructs can also be employed inside the template. In the following
script, the result() function sends a dictionary object to template results.html when URL
http://localhost:5000/result is opened in the browser.
The Template part of result.html employs a for loop to render key and value pairs of
dictionary object result{} as cells of an HTML table.
15
Flask
<!doctype html>
<html>
<body>
<table border=1>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
Here, again the Python statements corresponding to the For loop are enclosed in {%..%}
whereas, the expressions key and value are put inside {{ }}.
16
9. Flask Static Files Flask
A web application often requires a static file such as a javascript file or a CSS file
supporting the display of a web page. Usually, the web server is configured to serve them
for you, but during the development, these files are served from static folder in your
package or next to your module and it will be available at /static on the application.
<html>
<head>
<script type="text/javascript" src="{{ url_for('static',
filename=hrllo.js') }}" ></script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
function sayHello() {
alert("Hello World")
}
17
10. Flask Request Object Flask
The data from a clients web page is sent to the server as a global request object. In order
to process the request data, it should be imported from the Flask module.
Form: It is a dictionary object containing key and value pairs of form parameters
and their values.
args: parsed contents of query string which is part of URL after question mark (?).
18
11. Flask Sending Form Data to Template Flask
We have already seen that the http method can be specified in URL rule. The Form data
received by the triggered function can collect it in the form of a dictionary object and
forward it to a template to render it on a corresponding web page.
In the following example, / URL renders a web page (student.html) which has a form.
The data filled in it is posted to the /result URL which triggers the result() function.
The results() function collects form data present in request.form in a dictionary object
and sends it for rendering to table.html.
<html>
<body>
<form action="http://localhost:5000/result" method="POST">
<p>Name <input type="text" name="Name" /></p>
<p>Physics <input type="text" name="Physics" /></p>
<p>Chemistry<input type="text" name="chemistry" /></p>
<p>Maths <input type="text" name="Mathematics" /></p>
<p><input type="submit" value="submit" /></p>
</form>
</body>
19
Flask
</html>
<!doctype html>
<html>
<body>
<table border=1>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
Run the Python script and enter the URL http://localhost:5000/ in the browser.
20
Flask
When the Submit button is clicked, form data is rendered on result.html in the form of
HTML table.
21
12. Flask Cookies Flask
A cookie is stored on a clients computer in the form of a text file. Its purpose is to
remember and track data pertaining to a clients usage for better visitor experience and
site statistics.
A Request object contains a cookies attribute. It is a dictionary object of all the cookie
variables and their corresponding values, a client has transmitted. In addition to it, a
cookie also stores its expiry time, path and domain name of the site.
In Flask, cookies are set on response object. Use make_response() function to get
response object from return value of a view function. After that, use the set_cookie()
function of response object to store a cookie.
Reading back a cookie is easy. The get() method of request.cookies attribute is used to
read a cookie.
In the following Flask application, a simple form opens up as you visit / URL.
@app.route('/')
def index():
return render_template('index.html')
<html>
<body>
<form action="/setcookie" method="POST">
<p><h3>Enter userID</h3>
<p><input type='text' name='nm'/>
<p><input type='submit' value='Login'/>
</form>
</body>
</html>
The Form is posted to /setcookie URL. The associated view function sets a Cookie name
userID and renders another page.
22
Flask
resp.set_cookie('userID', user)
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome '+name+'</h1>'
23
Flask
24
13. Flask Sessions Flask
Unlike a Cookie, Session data is stored on server. Session is the time interval when a
client logs into a server and logs out of it. The data, which is needed to be held across this
session, is stored in a temporary directory on the server.
A session with each client is assigned a Session ID. The Session data is stored on top of
cookies and the server signs them cryptographically. For this encryption, a Flask
application needs a defined SECRET_KEY.
Session object is also a dictionary object containing key-value pairs of session variables
and associated values.
Session[username]=admin
session.pop('username', None)
The following code is a simple demonstration of session works in Flask. URL / simply
prompts user to log in, as session variable username is not set.
@app.route('/')
def index():
if 'username' in session:
username=session['username']
return 'Logged in as ' + username + '<br>' + \
"<b><a href='/logout'>click here to log out</a></b>"
return "You are not logged in <br><a href='/login'></b>" + \
"click here to log in</b></a>"
As user browses to /login the login() view function, because it is called through GET
method, opens up a login form.
A Form is posted back to /login and now session variable is set. Application is redirected
to /. This time session variable username is found.
25
Flask
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
The application also contains a logout() view function, which pops out username
session variable. Hence, / URL again shows the opening page.
@app.route('/logout')
def logout():
# remove the username from the session if it is there
session.pop('username', None)
return redirect(url_for('index'))
Run the application and visit the homepage. (Ensure to set secret_key of the application)
The output will be displayed as shown below. Click the link click here to log in.
26
Flask
27
14. Flask Redirect and Errors Flask
Flask class has a redirect() function. When called, it returns a response object and
redirects the user to another target location with specified status code.
HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
In the following example, the redirect() function is used to display the login page again
when a login attempt fails.
28
Flask
request.form['username']=='admin' :
return redirect(url_for('success'))
return redirect(url_for('index'))
@app.route('/success')
def success():
return 'logged in successfully'
if __name__ == '__main__':
app.run(debug=True)
Flask.abort(code)
Let us make a slight change in the login() function in the above code. Instead of re-
displaying the login page, if Unauthourized page is to be displayed, replace it with call
to abort(401).
29
Flask
abort(401)
else:
return redirect(url_for('index'))
@app.route('/success')
def success():
return 'logged in successfully'
if __name__ == '__main__':
app.run(debug=True)
30
15. Flask Message Flashing Flask
A good GUI based application provides feedback to a user about the interaction. For
example, the desktop applications use dialog or message box and JavaScript uses alerts
for similar purpose.
Generating such informative messages is easy in Flask web application. Flashing system
of Flask framework makes it possible to create a message in one view and render it in a
view function called next.
A Flask module contains flash() method. It passes a message to the next request, which
generally is a template.
flash(message, category)
Here,
get_flashed_messages(with_categories, category_filter)
Both parameters are optional. The first parameter is a tuple if received messages are
having category. The second parameter is useful to display only specific messages.
Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the
following code, a / URL displays link to the login page, with no message to flash.
@app.route('/')
def index():
return render_template('index.html')
31
Flask
The link leads a user to /login URL which displays a login form. When submitted, the
login() view function verifies a username and password and accordingly flashes a
success message or creates error variable.
Login.html
<!doctype html>
<html>
<body>
<h1>Login</h1>
{% if error %}
<p><strong>Error:</strong> {{ error }}
{% endif %}
<form action="" method=post>
<dl>
<dt>Username:
<dd><input type=text name=username value="{{request.form.username }}">
<dt>Password:
<dd><input type=password name=password>
</dl>
<p><input type=submit value=Login>
</form>
</body>
</html>
32
Flask
On the other hand, if login is successful, a success message is flashed on the index
template.
Index.html
<!doctype html>
<html>
<head>
<title>Flask Message flashing</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<h1>Flask Message Flashing Example</h1>
<p>Do you want to <a href="{{ url_for('login') }}"><b>log in?</b></a>
</body>
</html>
Flash.py
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
33
Flask
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
if __name__ == "__main__":
app.run(debug=True)
After executing the above codes, you will see the screen as shown below.
34
Flask
When you click on the link, you will be directed to the Login page.
35
16. Flask File Uploading Flask
Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute
set to multipart/form-data, posting the file to a URL. The URL handler fetches file from
request.files[] object and saves it to the desired location.
Each uploaded file is first saved in a temporary location on the server, before it is actually
saved to its ultimate location. Name of destination file can be hard-coded or can be
obtained from filename property of request.files[file] object. However, it is
recommended to obtain a secure version of it using the secure_filename() function.
It is possible to define the path of default upload folder and maximum size of uploaded file
in configuration settings of Flask object.
The following code has /upload URL rule that displays upload.html from the templates
folder, and /upload-file URL rule that calls uploader() function handling upload
process.
<html>
<body>
<form action="http://localhost:5000/uploader" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit"/>
</form>
</body>
</html>
36
Flask
Click Submit after choosing file. Forms post method invokes /upload_file URL. The
underlying function uploader() does the save operation.
37
17. Flask Extensions Flask
Flask is often referred to as a micro framework, because a core functionality includes WSGI
and routing based on Werkzeug and template engine based on Jinja2. In addition, Flask
framework has support for cookie and sessions as well as web helpers like JSON, static
files etc. Obviously, this is not enough for the development of a full-fledged web
application. This is where the Flask extensions come in picture. Flask extensions give
extensibility to Flask framework.
There are a large number of Flask extensions available. A Flask extension is a Python
module, which adds specific type of support to the Flask application. Flask Extension
Registry is a directory of extensions available. The required extension can be downloaded
by pip utility.
Flask Sijax: Interface for Sijax - Python/jQuery library that makes AJAX easy to
use in web applications
Each type of extension usually provides extensive documentation about its usage. Since
an extension is a Python module, it needs to be imported for it to be used. Flask extensions
are generally named as flask-foo. To import,
For versions of Flask later than 0.7, you can also use the syntax:
For this usage, a compatibility module needs to be activated. It can be installed by running
flaskext_compat.py
import flaskext_compat
flaskext_compat.activate()
from flask.ext import foo
38
18. Flask Mail Flask
A web based application is often required to have a feature of sending mail to the
users/clients. Flask-Mail extension makes it very easy to set up a simple interface with
any email server.
At first, Flask-Mail extension should be installed with the help of pip utility.
Mail class
It manages email-messaging requirements. The class constructor takes the following
form:
flask-mail.Mail(app=None)
39
Flask
Message class
It encapsulates an email message. Message class constructor has several parameters:
In the following example, SMTP server of Googles gmail service is used as MAIL_SERVER
for Flask-Mail configuration.
Step 1: Import Mail and Message class from flask-mail module in the code.
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = yourId@gmail.com'
app.config['MAIL_PASSWORD'] = '*****'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail=Mail(app)
40
Flask
Step 4: Set up a Message object in a Python function mapped by URL rule (/).
@app.route("/")
def index():
msg = Message(
'Hello',
sender='yourId@gmail.com',
recipients=
['id1@gmail.com'])
msg.body = "This is the email body"
mail.send(msg)
return "Sent"
Step 5: The entire code is given below. Run the following script in Python Shell and visit
http://localhost:5000/.
41
Flask
if __name__ == '__main__':
app.run(debug=True)
Note that the built-insecurity features in Gmail service may block this login attempt. You
may have to decrease the security level. Please log in to your Gmail account and visit this
link to decrease the security.
42
19. Flask WTF Flask
One of the essential aspects of a web application is to present a user interface for the user.
HTML provides a <form> tag, which is used to design an interface. A Forms elements
such as text input, radio, select etc. can be used appropriately.
Data entered by a user is submitted in the form of Http request message to the server
side script by either GET or POST method.
The Server side script has to recreate the form elements from http request data.
So in effect, form elements have to be defined twice once in HTML and again in
the server side script.
Another disadvantage of using HTML form is that it is difficult (if not impossible) to
render the form elements dynamically. HTML itself provides no way to validate a
users input.
This is where WTForms, a flexible form, rendering and validation library comes handy.
Flask-WTF extension provides a simple interface with this WTForms library.
Using Flask-WTF, we can define the form fields in our Python script and render them
using an HTML template. It is also possible to apply validation to the WTF field.
The installed package contains a Form class, which has to be used as a parent for user-
defined form.
WTforms package contains definitions of various form fields. Some Standard form
fields are listed below.
43
Flask
class ContactForm(Form):
In addition to the name field, a hidden field for CSRF token is created automatically. This
is to prevent Cross Site Request Forgery attack.
When rendered, this will result into an equivalent HTML script as shown below.
A user-defined form class is used in a Flask application and the form is rendered using a
template.
WTForms package also contains validator class. It is useful in applying validation to form
fields. Following list shows commonly used validators.
44
Flask
We shall now apply DataRequired validation rule for the name field in contact form.
The validate() function of form object validates the form data and throws the validation
errors if validation fails. The Error messages are sent to the template. In the HTML
template, error messages are rendered dynamically.
The following example demonstrates the concepts given above. The design of Contact
form is given below (forms.py).
45
Flask
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
return render_template('success.html')
elif request.method == 'GET':
return render_template('contact.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
<!doctype html>
<html>
<body>
<h2 style="text-align: center;">Contact Form</h2>
{% for message in form.name.errors %}
<div>{{ message }}</div>
{% endfor %}
{% for message in form.email.errors %}
<div>{{ message }}</div>
{% endfor %}
<form action="http://localhost:5000/contact" method=post>
<fieldset>
<legend>Contact Form</legend>
{{ form.hidden_tag() }}
<div style=font-size:20px;font-weight:bold;margin-left:150px;>
{{ form.name.label }}<br>
{{ form.name }}
<br>
{{ form.Gender.label }} {{ form.Gender }}
{{ form.Address.label }}<br>
{{ form.Address }}
<br>
{{ form.email.label }}<br>
{{ form.email }}
<br>
46
Flask
{{ form.Age.label }}<br>
{{ form.Age }}
<br>
{{ form.language.label }}<br>
{{ form.language }}
<br>
{{ form.submit }}
</div>
</fieldset>
</form>
</body>
</html>
47
Flask
If there are any errors, the page will look like this:
48
20. Flask SQLite Flask
Python has an in-built support for SQlite. SQlite3 module is shipped with Python
distribution. For a detailed tutorial on using SQLite database in Python, please refer to this
link. In this section we shall see how a Flask application interacts with SQLite.
import sqlite3
conn = sqlite3.connect('databsae.db')
print "Opened database successfully";
conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
print "Table created successfully";
conn.close()
First new_student() function is bound to the URL rule (/addnew). It renders an HTML
file containing student information form.
@app.route('/enternew')
def new_student():
return render_template('student.html')
<html>
<body>
<form action="{{ url_for('addrec') }}" method="POST">
<h3>Student Information</h3>
Name<br>
<input type="text" name="nm" /></br>
Address<br>
<textarea name="add" ></textarea><br>
City<br>
<input type="text" name="city" ><br>
PINCODE<br>
<input type="text" name="pin" ><br>
49
Flask
</form>
</body>
</html>
As it can be seen, form data is posted to the /addrec URL which binds the addrec()
function.
This addrec() function retrieves the forms data by POST method and inserts in students
table. Message corresponding to success or error in insert operation is rendered to
result.html.
@app.route('/addrec',methods=['POST', 'GET'])
def addrec():
if request.method=='POST':
try:
nm=request.form['nm']
addr=request.form['add']
city=request.form['city']
pin=request.form['pin']
with sql.connect("database.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO students (name,addr,city,pin) VALUES
(?,?,?,?)",(nm,addr,city,pin) )
con.commit()
msg= "Record successfully added"
except:
con.rollback()
msg= "error in insert operation"
finally:
return render_template("result.html",msg=msg)
con.close()
The HTML script of result.html contains an escaping statement {{msg}} that displays
the result of Insert operation.
<!doctype html>
<html>
<body>
result of addition : {{ msg }}
<h2><a href="\">go back to home page</a></h2>
</body>
50
Flask
</html>
The application contains another list() function represented by /list URL. It populates
rows as a MultiDict object containing all records in the students table. This object is
passed to the list.html template.
@app.route('/list')
def list():
con=sql.connect("database.db")
con.row_factory = sql.Row
cur = con.cursor()
cur.execute("select * from students")
rows=cur.fetchall();
return render_template("list.html",rows=rows)
This list.html is a template, which iterates over the row set and renders the data in an
HTML table.
<!doctype html>
<html>
<body>
<table border=1>
<thead>
<td>Name</td><td>Address</td><td>city</td><td>Pincode</td>
</thead>
{% for row in rows %}
<tr>
<td>{{row["name"]}}</td><td>{{row["addr"]}}</td><td> {{
row["city"]}}</td><td>{{row['pin']}}</td>
</tr>
{% endfor %}
</table>
<a href="/">Go back to home page</a>
</body>
</html>
51
Flask
Finally, the / URL rule renders a home.html which acts as the entry point of the
application.
@app.route('/')
def home():
return render_template('home.html')
52
Flask
@app.route('/list')
def list():
con=sql.connect("database.db")
con.row_factory = sql.Row
cur = con.cursor()
cur.execute("select * from students")
rows=cur.fetchall();
return render_template("list.html",rows=rows)
if __name__ == '__main__':
app.run(debug=True)
Run this script from Python shell and as the development server starts running. Visit
http://localhost:5000/ in browser which displays a simple menu like this:
Click Add New Record link to open the Student Information Form.
53
Flask
Fill the form fields and submit it. The underlying function inserts the record in the students
table.
Go back to the home page and click Show List link. The table showing the sample data
will be displayed.
54
21. Flask SQLAlchemy Flask
Using raw SQL in Flask web applications to perform CRUD operations on database can be
tedious. Instead, SQLAlchemy, a Python toolkit is a powerful OR Mapper that gives
application developers the full power and flexibility of SQL. Flask-SQLAlchemy is the Flask
extension that adds support for SQLAlchemy to your Flask application.
Most programming language platforms are object oriented. Data in RDBMS servers on the
other hand is stored as tables. Object relation mapping is a technique of mapping object
parameters to the underlying RDBMS table structure. An ORM API provides methods to
perform CRUD operations without having to write raw SQL statements.
In this section, we are going to study the ORM techniques of Flask-SQLAlchemy and build
a small web application.
Step 3: Now create a Flask application object and set URI for the database to be used.
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///students.sqlite3'
Step 4: Then create an object of SQLAlchemy class with application object as the
parameter. This object contains helper functions for ORM operations. It also provides a
parent Model class using which user defined models are declared. In the snippet below, a
students model is created.
db = SQLAlchemy(app)
class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key=True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))
def __init__(self, name, city, addr,pin):
self.name = name
self.city = city
55
Flask
self.addr = addr
self.pin = pin
Step 5: To create / use database mentioned in URI, run the create_all() method.
db.create_all()
The Session object of SQLAlchemy manages all persistence operations of ORM object.
You can apply a filter to the retrieved record set by using the filter attribute. For instance,
in order to retrieve records with city=Hyderabad in students table, use following
statement:
Students.query.filter_by(city=Hyderabad).all()
With this much of background, now we shall provide view functions for our application to
add a student data.
The entry point of the application is show_all() function bound to / URL. The Record
set of students table is sent as parameter to the HTML template. The Server side code in
the template renders the records in HTML table form.
@app.route('/')
def show_all():
return render_template('show_all.html', students = students.query.all() )
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
56
Flask
{{ message }}
{%- endfor %}
<h3>Students (<a href="{{ url_for('new') }}">Add Student</a>)</h3>
<table >
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Address</th>
<th>Pin</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.city }}</td>
<td>{{ student.addr }}</td>
<td>{{ student.pin }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
The above page contains a hyperlink to /new URL mapping new() function. When
clicked, it opens a Student Information form. The data is posted to the same URL in POST
method.
new.html
<!DOCTYPE html>
<html>
<body>
<h3 >Students - Flask SQLAlchemy example</h3>
</div>
<hr/>
{%- for category, message in get_flashed_messages(with_categories=true) %}
<div class="alert alert-danger">
{{ message }}
</div>
{%- endfor %}
57
Flask
When the http method is detected as POST, the form data is added in the students table
and the application returns to homepage showing the added data.
58
Flask
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///students.sqlite3'
app.config['SECRET_KEY']="random string"
db = SQLAlchemy(app)
class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key=True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))
def __init__(self, name, city, addr,pin):
self.name = name
self.city = city
self.addr = addr
self.pin = pin
@app.route('/')
def show_all():
return render_template('show_all.html', students=students.query.all() )
@app.route('/new', methods=['GET', 'POST'])
def new():
if request.method == 'POST':
if not request.form['name'] or not request.form['city'] or not
request.form['addr']:
flash('Please enter all the fields', 'error')
else:
student = students(request.form['name'],
request.form['city'],
request.form['addr'],
request.form['pin'])
db.session.add(student)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all'))
return render_template('new.html')
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
59
Flask
Run the script from Python shell and enter http://localhost:5000/ in the browser.
Fill the form and submit. The home page reappears with the submitted data.
60
Flask
61
22. Flask Sijax Flask
Sijax stands for Simple Ajax and it is a Python/jQuery library designed to help you
easily bring Ajax to your application. It uses jQuery.ajax to make AJAX requests.
Installation
Installation of Flask-Sijax is easy.
Configuration
SIJAX_STATIC_PATH the static path where you want the Sijax javascript files
to be mirrored. The default location is static/js/sijax. In this folder, sijax.js and
json2.js files are kept.
Sijax uses JSON to pass the data between the browser and the server. This means that
the browsers need either to support JSON natively or get JSON support from the json2.js
file.
Functions registered that way cannot provide Sijax functionality, because they cannot be
accessed using a POST method by default (and Sijax uses POST requests).
To make a View function capable of handling Sijax requests, make it accessible via POST
using @app.route('/url', methods=['GET', 'POST']) or use the @flask_sijax.route
helper decorator like this:
@flask_sijax.route(app, '/hello')
Every Sijax handler function (like this one) receives at least one parameter automatically,
much like Python passes self to the object methods. The obj_response parameter is
the function's way of talking back to the browser.
def say_hi(obj_response):
obj_response.alert('Hi there!')
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
62
Flask
Sijax Application
A minimal Sijax application code looks as follows:
import os
from flask import Flask, g
from flask_sijax import sijax
path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app = Flask(__name__)
app.config['SIJAX_STATIC_PATH'] = path
app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js'
flask_sijax.Sijax(app)
@app.route('/')
def index():
return 'Index'
@flask_sijax.route(app, '/hello')
def hello():
def say_hi(obj_response):
obj_response.alert('Hi there!')
if g.sijax.is_sijax_request:
# Sijax request detected - let Sijax handle it
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return _render_template('sijaxexample.html')
if __name__ == '__main__':
app.run(debug=True)
When a Sijax requests (a special jQuery.ajax() request) to the server, this request is
detected on the server by g.sijax.is_sijax_request(), in which case you let Sijax handle
the request.
All the functions registered using g.sijax.register_callback() are exposed for calling
from the browser.
63
23. Flask Deployment Flask
If debug is disabled, the development server on local computer can be made available to
the users on network by setting the host name as 0.0.0.0.
app.run(host=0.0.0.0)
Deployment
To switch over from a development environment to a full-fledged production environment,
an application needs to be deployed on a real web server. Depending upon what you have,
there are different options available to deploy a Flask web application.
For small application, you can consider deploying it on any of the following hosted
platforms, all of which offer free plan for small application.
Heroku
dotcloud
webfaction
If you are inclined to use a dedicated web server in place of above mentioned shared
platforms, following options are there to explore.
mod_wsgi
mod_wsgi is an Apache module that provides a WSGI compliant interface for hosting
Python based web applications on Apache server.
Installing mod_wsgi
To install an official release direct from PyPi, you can run:
64
Flask
To verify that the installation was successful, run the mod_wsgi-express script with the
start-server command:
mod_wsgi-express start-server
This will start up Apache/mod_wsgi on port 8000. You can then verify that the installation
worked by pointing your browser at:
http://localhost:8000/
Make sure that yourapplication and all the libraries that are in use are on the python
load path.
Configuring Apache
You need to tell mod_wsgi, the location of your application.
<VirtualHost *>
ServerName example.com
WSGIScriptAlias / C:\yourdir\yourapp.wsgi
<Directory C:\yourdir>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
Gunicorn
Tornado
Gevent
Twisted Web
65
24. Flask FastCGI Flask
FastCGI is another deployment option for Flask application on web servers like nginix,
lighttpd, and Cherokee.
Configuring FastCGI
First, you need to create the FastCGI server file. Let us call it yourapplication.fcgi.
nginx and older versions of lighttpd need a socket to be explicitly passed to communicate
with the FastCGI server. For that to work, you need to pass the path to the socket to the
WSGIServer.
WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()
Configuring Apache
For a basic Apache deployment, your .fcgi file will appear in your application URL e.g.
example.com/yourapplication.fcgi/hello/. There are few ways to configure your
application so that yourapplication.fcgi does not appear in the URL.
<VirtualHost *>
ServerName example.com
ScriptAlias / /path/to/yourapplication.fcgi/
</VirtualHost>
Configuring lighttpd
Basic configuration of lighttpd looks like this:
66
Flask
)
alias.url = (
"/static/" => "/path/to/your/static"
)
url.rewrite-once = (
"^(/static($|/.*))$" => "$1",
"^(/.*)$" => "/yourapplication.fcgi$1"
Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the
application to /yourapplication.
67