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.
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
Create a python file with the following code.
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
Now let us break down the cord in the python file.
flasklibrary, we imported
- We created flask application using
Flask()class constructor and stored it in the variable
- 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
- We called the
run()function on the flask application
appand passed host IP address
127.0.0.1and port number
This is just a basic application to understand how to build a flask application.
There are many concepts that we need to cover on flask. We shall cover these concepts in the following tutorials.
- Python Flask Example
- Python Flask Routes
- Python Flask Templates
- Python Flask – Send form data to template
- Python Flask – Send JSON as response
- Python Flask – Pass variables to templates
- Python Flask – Include CSS file in template
- Python Flask – Write Python code in template
- Python Flask – Include template in another template
- Python Flask – Accept only POST request
- Python Flask – Accept POST or GET request
- Python Flask – Get form values
- Python Flask – Read URL query parameters
- Python Flask – Accept variable in URL
- Python Flask – Upload file
- Python Flask – Redirect URL
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.