Python Flask Tutorial

by Apr 5, 2020Python

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

  1. What is Flask?
  2. Flask Environment Setup
  3. First Flask application
  4. App routing
  5. HTTP methods
  6. Templates
  7. Request Object
  8. 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.

  1. rule: It represents the URL binding with the function.
  2. 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
1hostThe default hostname is 127.0.0.1, i.e. localhost.
2portThe port number to which the server is listening to. The default port number is 5000.
3debugThe default is false. It provides debug information if it is set to true.
4optionsIt 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.

SNMethodDescription
1GETIt is the most common method which can be used to send data in the unencrypted form to the server.
2HEADIt is similar to the GET but used without the response body.
3POSTIt is used to send the form data to the server. The server does not cache the data transmitted using the post method.
4PUTIt is used to replace all the current representation of the target resource with the uploaded content.
5DELETE 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
1locationIt is the URL where the response will be redirected.
2status codeIt is the status code that is sent to the browser’s header along with the response from the server.
3responseIt 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.

Creating a multiplication Skill in Alexa using python

Written By Ashwin Raj

RELATED POSTS

Python Regular Expression

Python Regular Expression

Python is a general-purpose high-level programming language. Python is mainly used as a support language to software developers. It helps in building control and management and also in testing. The syntax python uses is very simple and similar to the English language....

Introduction to MicroPython and ESP8266

Introduction to MicroPython and ESP8266

For ages, C and C++ have ruled over the embedded system industry. Fast prototyping is an important aspect of the industry today. In fact MicroPython is the best suited for fast prototyping. Students and engineers are becoming very familiar with the Python programming...

Five Best Python Projects for Beginners

Five Best Python Projects for Beginners

Learning and practicing of any programming language can be monotonous. Also, only learning can not be the perfect gain of knowledge if we don't put it into some implementation. Likewise, Python programming language can be interesting but until we don't use it in some...

How to convert .py into .pyc? Compilation of Python Code

How to convert .py into .pyc? Compilation of Python Code

In this article we will see what is a pyc file ,how is it formed,how to convert and compile a pyc file. When we run a code in python it actually goes through a couple of steps before our program reaches the virtual machine It is compiled to bytecode.Then it is...

How to create and install a Python Package?

How to create and install a Python Package?

Requirements Check the tools pip --version pip install wheel What is Python Package Index? What is Distutils? Creating a Package Directory Structure some_root_dir/ |-- README |-- setup.py |-- an_example_pypi_project | |-- __init__.py | |-- useful_1.py | |--...

Docker for beginners tutorial:

Docker for beginners tutorial:

What is Docker? Docker, in simple words is a tool that allows developers who build applications, to package them with all their dependencies into a ‘container’ which can easily be shipped to run on the host operating . Containers do not have high overhead and allow...

Object-Oriented Programming in Python

Object-Oriented Programming in Python

Python Classes and Methods Python is an object-oriented programming language. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made....

Python Numbers

Python Numbers

In this article you will learn about types of numbers in python and their mathematical operations. So these are the contents of this article : Introduction Decimal Need of DecimalFractionsMathematics Introduction Python supports integer, floating-point number and...

Python File Handling

Python File Handling

In this article, we will discuss all about file handling in Python. Let us have a quick look at the contents shown below: IntroductionFile openSyntaxRead filesParts of file to readRead linesloopChoose filesWrite filesAppendSplitting wordsCreate a new fileSeek...

Python Lambda

Python Lambda

In this article, we will discuss on Python lambda. Let us have a quick look on the following contents shown below: IntroductionAdd two numbers using LambdaSum of 10 natural numbersMultiplicationSmaller of two numbers Introduction Lambda functions are the anonymous...

Python Functions

Python Functions

In this article, we will tell about Python functions. We should also know about function defining function calling and variable arguments. Let's have a quick look on the below contents : IntroductionFunction CreationDefinitionDeclarationCallArgumentsRequired...

Python While loop

Python While loop

In this article, we are going to focus on while loops used in python with suitable examples. The content of this article is shown below: IntroductionThe break statementContinue in whileElse in while loop Introduction While loop in Python is a primitive type of...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....