What is Python Flask and how to work with Python Flask

There are various web frameworks in market to create and build from simple to coolest applications using Python and one of them is Flask. In this tutorial you will learn what is Python Flask and how to work with Python Flask.

Table of Contents

  1. What is Web Framework?
  2. Why do we need Virtual Environment for Python?
  3. Prerequisites
  4. Installing and Setting up Python Flask on your machine
  5. Working with Python Flask (URL binding, URL redirection and debug mode)
  6. Working with Python Flask (HTTP METHOD: Rendering Templates /HTML PAGE)
  7. Working with Python Flask (HTTP METHOD: Rendering Templates and redirecting html page)
  8. Working with Python Flask (File Uploading)
  9. Conclusion

What is Web Framework?

The Simple answer is Framework is Code library which makes life of developer easy by reusing the code , extensions for operation to build a reliable , scalable and maintainable web apps. There are different Python Web frameworks such as FLASK , TORNADO, PYRAMID and DJANGO .

Why do we need Virtual Environment for Python?

When we create projects for Python we are dependent on several libraries and dependencies , so in order to work on particular project with specific versions of libraries and package it is recommended and a better approach to have separate virtual environment else applications with same libraries and version it may be break the functionalities.

Prerequisites

This post will be a step-by-step tutorial. If you’d like to follow along, ensure you have the following in place:

  • Python v3.6 or later – This tutorial will be using Python v3.9.2 on a Windows 10 machine. In case you don’t have Python installed then install it from here.
  • A code editor – This tutorial will use Visual Studio (VS) Code.

Installing and Setting up Python Flask on your machine

Now , you have idea to some extent about the Python Flask that is it is a web framework for Python. Next, let us work with it using some basic code and programs. Lets begin !

  • Assuming you are on your favorite code editor such as Visual Studio.
  • Before you write first python application on flask make sure you have virtual environment installed on your system. Python 3 comes with a virtual environment module called venv preinstalled so we will skip this step.
  • Next, create a environment named virt on your machine using below commands. This is different from the virtual environment.

py -3 -m venv virt
  • Now, Activate a virtual environment
  • Finally, Now Install Python flask on your machine by running the following command.
pip install flask # Install Flask from pip

Below distributions will be installed automatically when installing Flask.

  • Werkzeug implements WSGI, the standard Python interface between applications and servers.
  • Jinja is a template language that renders the pages your application serves.
  • MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks.

Lets learn few code components inside Python flask that are very important for flask developers.

  • app.route(rule, options)
    • The rule parameter represents URL binding with the function.
    • The options is a list of parameters to be forwarded to the underlying Rule object.
  • app.run(host, port, debug, options)
    • Host : (Default) 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally.
    • port : Defaults to 5000.
    • debug: Defaults to false. If set to true, provides a debug information.
    • options: To be forwarded to underlying server.

Working with Python Flask (URL binding, URL redirection and debug mode)

Lets learn how to work with URL binding, URL redirection and debug mode in python flask program.

  • Assuming you are still on code editor.
  • Create a folder on the visual studio code and name it as Flask and under that create a file such as flask.py
# CREATE A FLASK APPLICATION

from flask import Flask, url_for # Importing the class flask 
from markupsafe import escape

# Creating Flask class object/instance. The first argument is name of application’s module or package
app = Flask(__name__) 

# route() tell Flask what URL should trigger our function.
@app.route('/home') 
def home():
    return "This is my First Flask Website but Actually, I own Automateinfra.com"
@app.route('/login')
def login():
    return "This is my login page"
@app.route('/user/<username>') # Function receives <variable_name> as a keyword argument
def profile(username):
    return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def post_id(post_id):
    return 'Post %d' % post_id

# To build a URL to a specific function, use the url_for() function.
with app.test_request_context(): 
    print(url_for('home'))
    print(url_for('login'))
    print(url_for('profile', username = 'Automate Infra'))
    print(url_for('post_id', post_id = '100'))

if __name__ =='__main__':
    app.run(debug=True)
  • Execute the flask program by running the command on visual studio terminal as below.
python flask.py
O/P on Visual Studio Code Terminal:

* Serving Flask app "application2" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
/home
/login
/user/Automate%20Infra
/post/100
 * Debugger is active!
 * Debugger PIN: 285-837-988
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Working with Python Flask (HTTP METHOD: Rendering Templates /HTML PAGE)

Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the Jinja template library to render templates.

  • Assuming you are still on code editor. Create one folder templates and under that create another file hello.html and paste the below content.
# THIS IS MY HTML FILE WHICH IS BEING USED IN FLASK APP BELOW

<!DOCTYPE html>

<title>Hello Welcome</title>
{% if name %}
<h1>Hello {{name}} , Welcome </h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
  • Create a one more file and name it as application.py and paste the below content.
from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')

def hello(name=None):
    return render_template('hello.html', name=name)

if __name__ =='__main__':
   app.run(debug=True)

Your folder structure should like below.

  • Execute the flask program by running the command on visual studio terminal as below.
python render_html.py
  • Navigate to the browser and open 127.0.0.1:5000/hello and 127.0.0.1:5000/hello/<name> and you should see the output as below.

Working with Python Flask (HTTP METHOD: Rendering Templates and redirecting html page)

Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.

  • Assuming you are still on code editor. Create another file code.html and paste the below content.
# This is my HTML Page

<html>
  <body>
    <form action="http://localhost:5000/login" method="post">
      <p>Please Enter your name</p>
      <p><input type="text" name="automateinfra" /></p>
      <p><input type="submit" value="Submit" /></p>
    </form>
  </body>
</html>

  • Create a one more file and name it as render_redirection_html.py and paste the below content.
  • # MY FLASK APPLICATION 
    
    from flask import Flask , redirect , url_for , request
    app = Flask(__name__)
    
    @app.route('/success/<name>')
    def success(name):
        return 'welcome %s' % name
    
    @app.route('/login', methods = ['GET','POST'])
    def login():
        if request.method == 'POST':
           user = request.form['automateinfra']
           return redirect(url_for('success', name = user)) 
        else:
           return "INVALID"
      
    if __name__ == '__main__':
       app.run(debug = True)
    • Now execute the python program by running the following command.
    python render_redirection_html.py
    • Simultaneously run html page which you created in any browser and provide the name as automateinfra

    As soon as you Submit the form see the response as below in Python Terminal as below.

    
    
    * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 285-837-988
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    127.0.0.1 - - [16/Jan/2021 23:28:38] "POST /login HTTP/1.1" 302 -
    127.0.0.1 - - [16/Jan/2021 23:28:38] "GET /success/Automate%20infra HTTP/1.1" 200 -
    

    On browser, you will notice that when form is submitted it gets redirected to the Flask application.

    Working with Python Flask (File Uploading)

    Let’s start with a very basic application that uploads a file to a specific upload folder and displays a file to the user.

  • Assuming you are still on code editor. Create another file upload.html and paste the below content.
  • <html>
       <body>
          <form action = "http://localhost:5000/success" method = "POST" 
             enctype = "multipart/form-data">
             <input type = "file" name = "file" />
             <input type = "submit"/>
          </form>   
       </body>
    </html>

  • Create a one more file and name it as file_upload.py and paste the below content.
  • from flask import *  
    app = Flask(__name__)  
     
    @app.route('/upload')  
    def upload():  
        return render_template('upload.html')  
     
    @app.route('/success', methods = ['POST'])  
    def success():  
        if request.method == 'POST':  
            f = request.files['file']  
            f.save(f.filename)  
            return render_template('success.html', name = f.filename)  
      
    if __name__ == '__main__':  
        app.run(debug = True) 
    • Now, execute the python script using below command
    python file_upload.py
    • Now click on Submit.

    Conclusion

    In this tutorial you learnt what is Python flask and how to install flask on your windows machine. Finally you learnt how to work with Python flask such as URL binding, URL redirection and debug mode , Rendering Templates and redirecting html page and file uploading.

    Hope this tutorial was helpful and please share if you like it.

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google photo

    You are commenting using your Google account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    Connecting to %s