Ubuntu

How to Install and Use Flask on Ubuntu 22.04

Flask is a Python framework that is used to design and test different web applications based on the Python programming language. If you are a beginner, then Flask is the best platform for you through which you can learn how to maintain and develop different web applications in a scalable, secure way.

In this guide, we will discover the method to install the Linux package of Flask on Ubuntu using the command-line interface.

How to install Flask on Ubuntu 22.04 using the Python environment

First of all, we will confirm the installed version of Python in our Ubuntu by using the command:

$ python3 --version

We have checked the Python version because Python is the dependency of Flask and is necessary to be installed before the installation of Flask; next we will install “pip” and “Python environment” using the command:

$ sudo apt install python3-venv pip -y

Now, we will create a folder with “LinuxHint_Flask” and navigate to it with the cd command:

$ mkdir LinuxHint_Flask && cd LinuxHint_Flask

In the new folder, create a Python environment for Flask application and also activate it to use the application:

$ python3 -m venv venv && source venv/bin/activate

When the Python environment is activated, we will use “pip” to install the Python package of Flask:

$ pip install Flask

To check the version of installed Flask, we will run the command:

$ python -m flask --version

How to make a simple Python application using Flask

To understand the working of Flask, we will create a simple application which will display a message “Welcome to LinuxHint-Flask tutorial”, for this purpose, open the nano text editor:

$ nano Flask_application

In the open text file, type the statements mentioned below:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def my_flask_application():
    return 'Welcome to LinuxHint-Flask tutorial'

Exit the editor by saving the file. In the above code, first, we imported the library of a Flask, then we created a class of Flask, and lastly by using the route(), we printed the message on the screen. To export the application with the name “Flask_application”, we will use the command:

$ export FLASK_APP=Flask_application.py

Run the Flask application using the command:

$ flask run

Open the web browser and go to the URL http://127.0.0.1:5000:

The message has been displayed and now, we will uninstall Flask and deactivate the Python environment by executing the command:

$ pip uninstall Flask && deactivate

Conclusion

Flask is the web framework that is used to design and maintain different web applications based on the Python programming language. In this guide, we have installed and learned the method of designing a simple application with the help of Flask.

About the author

Hammad Zahid

I'm an Engineering graduate and my passion for IT has brought me to Linux. Now here I'm learning and sharing my knowledge with the world.