Simplifying Django dependencies with virtualenv

books in a stack (a stack of books) by austinevanvirtualenv is a tool for simplifying dependency management in Python applications. As the name suggests, virtualenv creates a virtual environment which makes it easy to install Python packages without needing root privileges to do so.

To use the packages installed in a virtual environment you run the activate script in the bin directory of the virtual environment. This is fine when you’re working on the command line, but you don’t want to have to remember this step when running the debug server, and it’s hard to get that to work when the site is deployed under mod_wsgi.

To make things easier you can add the appropriate directory from the virtual environment to Python’s path as part of, or the appropriate fcgi or wsgi control script.

import os
import sys
import site

root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

site.addsitedir(os.path.join(root_dir, 've/lib/python%i.%i/site-packages' % (sys.version_info[0], sys.version_info[1])))

Just add the code above to the top of your file and the ve virtual environment will always be activated when you run the script.

Photo of books in a stack (a stack of books) by austinevan.


Author: Andrew Wilkinson

I'm a computer programmer and team leader working at the UK grocer and tech company, Ocado Technology. I mostly write multithreaded real time systems in Java, but in the past I've worked with C#, C++ and Python.

One thought on “Simplifying Django dependencies with virtualenv”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s