Our most recent course, Advanced REST APIs with Flask and Python, uses Pipenv.

However, the "beginner" course—REST APIs with Flask and Python—used virtualenv.

This blog post is to help students of the first course migrate to Pipenv, since that's used in the second course.

Why Pipenv?

There are two main reasons to migrate to Pipenv for this course, and for small application development. There are more reasons to migrate when doing larger applications.

The two main reasons to migrate for this course are:

  • It's easier to work with Pipenv than virtualenv and pip, because it creates the virtual environments for you and manages them too;
  • It's safer to use Pipenv than virtualenv, because every dependency installed has a hash which is saved in a file called Pipfile.lock. When downloading the dependency, if it does not match the hash for that version, it won't work. This way you can know if the dependency has in some way been modified but the version number has not changed.

Safer?

A dependency can change without its version number changing if, for example, someone hacks into where the dependency is stored and modifies the dependency without you knowing.

Malicious code could be added without anybody knowing, and that is dangerous.

With Pipfile.lock, every dependency has a hash that is generated from the package contents—so if the package contents change, the hash would change. Pipenv checks this when installing to make sure that you are installing the dependencies you think you are.

Migrating to Pipenv

Migrating to Pipenv is actually really easy. All you have to do is:

  • Install Pipenv (pip install pipenv);
  • Run pipenv install on the same folder that you have your requirements.txt file;
  • Delete your requirements.txt file, as now you have Pipfile and Pipfile.lock files.

Running your app with Pipenv

When using pip and virtualenv, we would normally activate the virtualenv first, and then run our Python app.

With Pipenv, you can do pipenv run python app.py to do it in one go.

Optionally, you can activate the virtualenv by running pipenv shell. Then run your application in the same way as when you were using virtualenv.

Generating a requirements.txt file

Some software services may require requirements.txt files to be provided (e.g. ReadTheDocs, Heroku...). Generating a requirements.txt file with Pipenv is very easy:

pipenv lock --requirements > requirements.txt

Other reading material