Ruan Bekker's Blog

From a Curious mind to Posts on Github

Python Flask Tutorial Series: Setup a Python Virtual Environment

In our previous post we wrote a basic Hello World App in Flask. This is post 2 of the Python Flask Tutorial Series

In this section we will be covering our Environment Setup, where I will be showing you how to setup a typical Python Flask Environment using virtualenv

What is VirtualEnv?

Virtualenv allows you to have isolated Python Environments, where each project or environment can have their own versions. Some applications may need a specific version of a certain package, so lets say you are running multiple applications on one server, then having to manage each ones dependencies can be a pain. As you may run into scenarios where they are dependent on specific versions, where you have to upgrade/downgrade packages like no-ones business.

Luckily with the help of virtualenv, each environment is isolated from each other, so system wide you might be running Python 2.7 with minimal packages installed, then you can create a virtual environment with Python 3 with packages for the application you are developing.

Setup a Virtual Environment:

We will setup a virtualenv for our project with our default python version which in this case is 2.7:

1
2
3
$ mkdir ~/projects/mywebapp
$ cd ~/projects/mywebapp
$ virtualenv .venv

At this moment you should have your virtual environment ready, now to enter and activate our environment:

1
$ source .venv/bin/activate

To confirm your python version:

1
2
$ python --version
Python 2.7.6

If you have multiple versions of python, you can create your virtual environment with a different python version by using the -p flag, as in:

1
$ virtualenv -p /usr/local/bin/python2.7 .venv

Now that we are in our virtualenv, lets install 2 packages, Flask and Requests:

1
2
$ pip install flask
$ pip install requests

With pip we can list the installed packages we have with pip freeze. Since this is our virtual environment, we will only see the packages that was installed into this environment:

1
2
3
4
5
6
7
8
9
10
$ pip freeze
click==6.7
Flask==0.12
itsdangerous==0.24
Jinja2==2.9.5.1
MarkupSafe==1.0
requests==2.7.0
six==1.10.0
virtualenv==15.0.1
Werkzeug==0.12.1

We can dump this to a file, which we can later use to install packages from a list so that we don’t have to specify them manually. We can dump them by doing this:

1
$ pip freeze > requirements.txt

Now lets say you are on a different host and you would like to install the packages from the requirements.txt file, we do this by using the following command:

1
$ pip install -r requirements.txt

To exit your virtualenv, you do the following:

1
$ deactivate

I hope this was useful, next up in our Python Flask Tutorial Series will be Routing in Flask