In this tutorial, we will install flask in a virtual environment. There are a number of advantages of working in a virtual environment -

  1. Firstly, we can set different configurations for each virtual environment. The packages installed in the virtual environment are not accessible outside it. It guarantees there are no conflicts with the global interpreter.
  2. To install new packages, virtual environments don’t require root privileges.

Let’s start by creating a virtual environment -

cd ~
sudo apt-get install python-virtualenv 
sudo apt-get install python-pip

To check if virtualenv is correctly installed, type -

virtualenv --version

At the time this post was written, the output was -

1.11.4

Now let’s make a directory flask-application where we will store our project.

mkdir flask-application
cd flask-application

It time to create to virtual environment flask-env, where we will install flask.

virtualenv flask-env

You will see the following output on the terminal -

New python executable in flask-env/bin/python
Installing setuptools, pip...done.

We have successfully created our virtual environment, now let’s activate it using the command below -

source flask-env/bin/activate

You will now notice that on left side of your command prompt, (flask-env) appears. So now, when you install a package, it will only be accessible from the virtual environment. When you exit the virtual environment, you can no longer access any package you install inside the virtual environment. It is time to install flask. We will use pip to install the package -

pip install Flask

Let’s write a hello.py  script which prints "Hello World!" when we open http://127.0.0.1:5000/ in the browser -

from flask import Flask

app = Flask(__name__)

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

if (__name__ == "__main__"):
app.run(port = 5000)

Run the python script using -

python hello.py

In the browser, open the url http://127.0.0.1:5000/. The result looks like this -

Webpage at localhost:5000
Figure 1: Webpage at localhost:5000 [PNG]

To deactivate the virtual environment, type the below line in the command prompt -

deactivate