Flask is a web framework that provides libraries to build lightweight web applications in python. It is developed by Armin Ronacher who leads an international group of Python enthusiasts (POCCO).
Contents
- What is Flask?
- Flask Environment Setup
- First Flask application
- App routing
- HTTP methods
- Templates
- Request Object
- Redirect and Errors
1. What is Flask?
What is Jinja2?
Jinja2 is a web template engine that combines a template with a certain data source to render the dynamic web pages.
2. Flask Environment Setup
To install flask on the system, we need to have python 2.7 or higher installed on our system. However, we suggest using python 3 for the development in the flask.
Install virtual environment (virtualenv)
virtualenv is considered as the virtual python environment builder which is used to create the multiple python virtual environment side by side. It can be installed by using the following command.
pip install virtualenv
Once it is installed, we can create the new virtual environment into a folder as given below.
$ mkdir new
$ cd new
$ virtualenv venv
To activate the corresponding environment, use the following command on the Linux operating system
$ venv/bin/activate
On windows, use the following command.
$ venv\scripts\activate
We can now install the flask by using the following command.
$ pip install flask
To test the flask installation, open python on the command line and type python to open the python shell. Try to import the package flask.
3. First Flask application
In this section of the tutorial, we will build our first python website built using the Flask framework. In this process, open any text editor of your choice as we are using the sublime text editor in this tutorial.
Write the following lines of code and save it to a file named script.py.
from flask import Flask
app = Flask(__name__) #creating the Flask class object
@app.route('/') #decorator drfines the
def home():
return "hello, this is our first flask website";
if __name__ =='__main__':
app.run(debug = True)
To build the python web application, we need to import the Flask module. An object of the Flask class is considered as the WSGI application.
We need to pass the name of the current module, i.e. __name__ as the argument into the Flask constructor.
4. App Routing
The route() function of the Flask class defines the URL mapping of the associated function. The syntax is given below.
app.route(rule, options)
It accepts the following parameters.
- rule: It represents the URL binding with the function.
- options: It represents the list of parameters to be associated with the rule object
Finally, the run method of the Flask class is used to run the flask application on the local development server.
app.run(host, port, debug, options)
SN | Option | Description |
---|---|---|
1 | host | The default hostname is 127.0.0.1, i.e. localhost. |
2 | port | The port number to which the server is listening to. The default port number is 5000. |
3 | debug | The default is false. It provides debug information if it is set to true. |
4 | options | It contains the information to be forwarded to the server. |
App routing is used to map the specific URL with the associated function that is intended to perform some task. It is used to access some particular page like Flask Tutorial in the web application.
In our first application, the URL (‘/’) is associated with the home function that returns a particular string displayed on the web page.
In other words, we can say that if we visit the particular URL mapped to some particular function, the output of that function is rendered on the browser’s screen.
Example
from flask import Flask
app = Flask(__name__)
@app.route('/home')
def home():
return "hello, welcome to our website";
if __name__ =="__main__":
app.run(debug = True)
Flask facilitates us to add the variable part to the URL by using the section. We can reuse the variable by adding that as a parameter into the view function. Consider the following example.
from flask import Flask
app = Flask(__name__)
@app.route('/home/<name>')
def home(name):
return "hello,"+name;
if __name__ =="__main__":
app.run(debug = True)
5. HTTP methods
HTTP is the hypertext transfer protocol which is considered as the foundation of the data transfer in the world wide web. All web frameworks including flask need to provide several HTTP methods for data communication.
The methods are given in the following table.
SN | Method | Description |
---|---|---|
1 | GET | It is the most common method which can be used to send data in the unencrypted form to the server. |
2 | HEAD | It is similar to the GET but used without the response body. |
3 | POST | It is used to send the form data to the server. The server does not cache the data transmitted using the post method. |
4 | PUT | It is used to replace all the current representation of the target resource with the uploaded content. |
5 | DELETE | It is used to delete all the current representation of the target resource specified in the URL. |
POST Method
To handle the POST requests at the server, let us first create a form to get some data at the client-side from the user, and we will try to access this data on the server by using the POST request.
login.html
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<table>
<tr><td>Name</td>
<td><input type ="text" name ="uname"></td></tr>
<tr><td>Password</td>
<td><input type ="password" name ="pass"></td></tr>
<tr><td><input type = "submit"></td></tr>
</table>
</form>
</body>
</html>
Now, Enter the following code into the script named post_example.py.
post_example.py
from flask import *
app = Flask(__name__)
@app.route('/login',methods = ['POST'])
def login():
uname=request.form['uname']
passwrd=request.form['pass']
if uname=="Rahul" and passwrd=="google":
return "Welcome %s" %uname
if __name__ == '__main__':
app.run(debug = True)
GET Method
Let’s consider the same example for the GET method. However, there are some changes in the data retrieval syntax on the server-side. First, create a form as login.html.
login.html
<html>
<body>
<form action = "http://localhost:5000/login" method = "get">
<table>
<tr><td>Name</td>
<td><input type ="text" name ="uname"></td></tr>
<tr><td>Password</td>
<td><input type ="password" name ="pass"></td></tr>
<tr><td><input type = "submit"></td></tr>
</table>
</form>
</body>
</html>
Now, create the following python script as get_example.py.
get_example.py
from flask import *
app = Flask(__name__)
@app.route('/login',methods = ['GET'])
def login():
uname=request.args.get('uname')
passwrd=request.args.get('pass')
if uname=="Rahul" and passwrd=="google":
return "Welcome %s" %uname
if __name__ == '__main__':
app.run(debug = True)
After clicking submit button as in previous case
An important difference between the GET requests and the POST requests as the data sent to the server is not shown in the URL on the browser in the POST requests.
6. Templates
Flask makes uses of the Jinja2 template engine. It’s simply HTML with variables and other programming constructs like conditional statement and this allows you to so some logic in the template itself. The template language is then rendered into plain HTML before being sent to the client.
Create a server.py
file and add the following code:
import os
from flask import Flask, render_template
app = Flask(name)
@app.route("/")
def index():
return render_template("index.html", message="Hello Flask!");
if name == "main":
app.run(host='0.0.0.0', port=8000, debug=True)
We use the render_template()
method to render the index.html
template which we’ll be creating in the templates
folder of our project. Optionally, we can pass variables like the message
variable that will be available to the template.
Next, create a templates
folder and add an index.html
file with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template Example</title>
</head>
<body>
<div>
<p>{{ message }}</p>
</div>
</body>
</html>
Rendering external HTML files
Example
To render an HTML file from the view function, let’s first create an HTML file named as message.html.
message.html
<html>
<head>
<title>Message</title>
</head>
<body>
<h1>hi, welcome to the website </h1>
</body>
</html>
script.py
from flask import *
app = Flask(__name__)
@app.route('/')
def message():
return render_template('message.html')
if __name__ == '__main__':
app.run(debug = True)
7. Request Object
The data from a client’s 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.
Important attributes of request object are listed below −
- 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 the question mark (?).
- Cookies − dictionary object holding Cookie names and values.
- files − data pertaining to uploaded files.
- method − current request method.
8. Redirect and Errors
Flask class provides the redirect() function which redirects the user to some specified URL with the specified status code.
The syntax to use the redirect() function is given below.
Flask.redirect(<location>,<status-code>, <response> )
It accepts the following parameters.
SN | Parameter | Description |
---|---|---|
1 | location | It is the URL where the response will be redirected. |
2 | status code | It is the status code that is sent to the browser’s header along with the response from the server. |
3 | response | It is the instance of the response that is used in the project for future requirements. |
Example
login.py
from flask import *
app = Flask(__name__)
@app.route('/')
def home ():
return render_template("home.html")
@app.route('/login')
def login():
return render_template("login.html");
@app.route('/validate', methods = ["POST"])
def validate():
if request.method == 'POST' and request.form['pass'] == 'qwert':
return redirect(url_for("success"))
return redirect(url_for("login"))
@app.route('/success')
def success():
return "logged in successfully"
if __name__ == '__main__':
app.run(debug = True)
home.html
<html>
<head>
<title>home</title>
</head>
<body>
<h3>Welcome to the website</h3>
<a href = "/login">login</a><br>
</html>
login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/validate">
<table>
<tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>
<tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>
The login page contains shown in the below image prompts the user to enter the email and password, and the submit button redirects the user to URL /validate.
In this case, as I have entered a random password not equal to ‘qwert’ therefore, the user reverts to this page (login page) only. However, the user is redirected to the URL /success only if the password entered by the user to ‘qwert’. The message displayed on the screen will be ‘logged in successfully’.
Standard HTTP Codes
- 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
The default status code is HTTP_302_FOUND.