Tuesday, April 3, 2012

Virtual Environment for Django and python with version specified.

Python2.6 is the default Python version on Ubuntu 10.04. Now you may still want to run your Django websites with Python2.5. A nice way to do this is by creating virtual environments to handle $PYTHONPATH and avoid conflicts among different versions. Such a tool already exists: Virtualenvwrapper.

First, to install Virtualenvwrapper, we will need easy_install:
$ sudo apt-get install python-setuptools
$ sudo easy_install virtualenv
$ sudo easy_install virtualenvwrapper
$ mkdir ~/.virtualenvs
We just need to add the following lines to .bashrc.
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
And run it.
$ source .bashrc
We then create a virtual environment, here named django with Python2.5. Python2.6 is the default version on Ubuntu 10.04.

To create virtual environment 
    here -p specifies the package
$ mkvirtualenv -p python2.5 django
To use virtual environment named "django"
  bracket contains the current virtual environment
$ workon django
To close virtual environment named "django"
$ (django)...:$ deactivate
We are ready to go with Python 2.5. workon sets the current virtual environment and deactivate exits from it.

We can now add some additional Python paths on our virtual environment, for example:
$ workon django
$ (django)...:$ add2virtualenv /home/user/additional_python_path
$ (django)...:$ add2virtualenv
Usage: add2virtualenv dir [dir ...]
Existing paths:
home/user/additional_python_path
$ (django)...:$
Finally here are some other useful commands:
$ mkvirtualenv django2
$ rmvirtualenv django2
$ workon django
$ (django)...:$ deactivate
$ workon
django
Now The most important thing is "How to use virtualenv in
production ???"

For that you will need to add it's path to your PYTHONPATH.
For example if your env had for path "/home/www/my_project/env/", the path to add would be:
/home/www/env/lib/python2.7/site-packages/
You can set this up in many different ways, but if your are generating your fcgi or uwsgi interface through manage.py, simply add the following at the very top of your manage.py (before the rest):
import os
my_virtualenv_path
= "/home/www/my_project/env/lib/python2.7/site-packages/"
# Add it to your PYTHONPATH
os
.path.append(my_virtualenv_path)
You can adopt this to whatever your setup is, just in case you could also do the following in the shell :
export PYTHONPATH:$PYTHONPATH:/home/www/my_project/env/lib/python2.7/site-packages/
You will also need to add the directory of where your settings.py file is located to the PYTHONPATH, so django will be able to discover it, just proceed in a similar manner to do so.

6 comments: