Python Flask Tutorial

Flask Tutorial

In python flask framework is used to build light web applications.

In this tutorial, we will learn how to install flask, using PIP, and build a lightweight, Web application to demonstrate the working of flask framework.

Prerequisites

Python has to be installed in your computer. This is the only prerequisite for this tutorial.

Install flask using PIP

Run the following command to install flask in your system.

$ pip install flask

Flask Hello World Application

We will build a simple, and lightweight Web application, where the server responds with the message "Hello World".

Create a python file with the following code.

main.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello World"

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

Open a Terminal and run this python program.

Now the flask application is running on localhost at port 8080.

Open web browser of your choice and enter the URL http://127.0.0.1:8080.

For the route / URL, the server has responded with a message Hello World.

Now let us break down the cord in the python file.

  1. From flask library, we imported Flask class.
  2. We created flask application using Flask() class constructor and stored it in the variable app.
  3. We defined a function index() that is called for the root URL "/", which in this case would be http://127.0.0.1:8080, and returns string "Hello World".
  4. We called the run() function on the flask application app and passed host IP address 127.0.0.1 and port number 8080 as arguments.

This is just a basic application to understand how to build a flask application.

Flask Tutorials

There are many concepts that we need to cover on flask. We shall cover these concepts in the following tutorials.

  1. Python Flask Example
  2. Python Flask Routes
  3. Python Flask Templates
  4. Python Flask – Send form data to template
  5. Python Flask – Send JSON as response
  6. Python Flask – Pass variables to templates
  7. Python Flask – Include CSS file in template
  8. Python Flask – Write Python code in template
  9. Python Flask – Include template in another template
  10. Python Flask – Accept only POST request
  11. Python Flask – Accept POST or GET request
  12. Python Flask – Get form values
  13. Python Flask – Read URL query parameters
  14. Python Flask – Accept variable in URL
  15. Python Flask – Upload file
  16. Python Flask – Redirect URL

Summary

In this Python Tutorial, we learned about flask Library in Python, learned how to build a flask application with the help of an example, and listed some flask tutorials that cover most encountered use cases when building a web application.