Skip to content

Instantly share code, notes, and snippets.

@carljm
Created January 27, 2011 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carljm/799045 to your computer and use it in GitHub Desktop.
Save carljm/799045 to your computer and use it in GitHub Desktop.
A mod_wsgi deployment file for Django that handles a virtualenv, putting its paths in front
import os, sys, site
base = os.path.dirname(os.path.dirname(__file__))
project = os.path.join(base, 'project')
virtenv = os.path.join(base, 'env')
### virtual environment, with precedence over global env ###
# from http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
ALLDIRS = [os.path.join(virtenv, 'lib',
'python%s' % sys.version[:3],
'site-packages')]
# Remember original sys.path.
prev_sys_path = list(sys.path)
# Add project directory
sys.path.append(project)
# Add each new site-packages directory.
for directory in ALLDIRS:
site.addsitedir(directory)
# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
### end virtualenv support ###
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
@acdha
Copy link

acdha commented Jan 27, 2011

Interesting approach - I've typically just used WSGIDaemons with the python lib path set to the virtualenv. Now I want to compare the two on a big project.

@carljm
Copy link
Author

carljm commented Jan 27, 2011

One difference is that addsitedir processes .pth files, so it mirrors the behavior of the real virtualenv more closely. This probably doesn't affect anything unless you have some easy-installed eggs or editable (develop) installs in your virtualenv; those won't work unless you use addsitedir (unless mod_wsgi does some magic I'm unaware of to call addsitedir on the python lib path you give it; in which case I'd expect that approach, rather than the above, to be recommended in their docs).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment