How to install Flask in Ubuntu 18.04

How to install Flask in Ubuntu 18.04

Ubuntu version : 18.04
Python version: 3.6.7

Let’s get started from Ubuntu. If you are in ubuntu server and type below command you will see the version of your current python installation.

python3 -V

In my case, it was Python 3.6.9.

Now we need to install ‘virtualenv’ module.
(There are several approaches that we can set a virtual environment for python, but it seems like this one is recommended these days.)

sudo apt install python3-venv

Then, we make our project directory.

mkdir myapp
cd myapp

In side the project directory, we need to install virtual environment using following command.
(The second ‘venv’ can be named however you want)

python3 -m venv venv

Okay, if you are not familiar with virtualenv in Python, here is the confusing part. When you are installing some python packages, you don’t want to install them globally on your system. You only want to install them in a certain closed environment for each project.

The reason we are using a virtual environment is to make your project independent of your system environment. In other words, it will enhance the portability of your project.

Once you have set the virtual environment, the project can be installed seamlessly on macOS, Windows, and Linux systems later.

Now we activate our virtual environment using following command.

source venv/bin/activate

Then, you will see (venv) sign is in front of your current cursor like below.

From now on, all the pip related commands will effect only on your virtual environment not the global system environment.

Now we can install flask using following command.

pip install Flask

Check if it is installed.

python -m flask --version

Then make a python file called ‘app.py’.

vi app.py

Copy and past the following code.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

Escape the vi editor by typing ‘:wq’

Then finally set the enviromental variable so that flask can point out the app.py app.

And flask run command will run the flask app.

export FLASK_APP=app
flask run

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: