Django Apache and Virtualenv ImportError: No module named site

Jabda picture Jabda · Dec 6, 2016 · Viewed 18.5k times · Source

The error from apache after a 504 page

[info] mod_wsgi (pid=): Python home /var/venv/mybox.
[info] mod_wsgi (pid=): Initializing Python.
ImportError: No module named site

This is with a barely configured app.

<IfModule mod_wsgi.c>
WSGIDaemonProcess myapp python-home=/var/venv/mybox
WSGIProcessGroup myapp
WSGIScriptAlias / /var/www/html/web/myapp/wsgi.py
WSGISocketPrefix /var/run/wsgi

<Directory /var/www/html/web>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
</IfModule>

Followed every post and tutorial I can. I am on CENTOS6 . using virutal env python 2.7 the default system env is 2.6

$ ldd /etc/httpd/modules/mod_wsgi.so
  linux-vdso.so.1 =>  (0x00007ffc06174000)

mywsgi.py

 import os,sys     
 from django.core.wsgi import get_wsgi_application     
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
 sys.path.insert(0,'/var/www/html/web')
 activate_this = '/var/venv/mybox/bin/activate_this.py'
 execfile(activate_this, dict(__file__=activate_this))
 application = get_wsgi_application()

PYHTONHOME is not set

Answer

Graham Dumpleton picture Graham Dumpleton · Dec 6, 2016

The documentation for using virtual environments with mod_wsgi can be found at:

Most important in your case is the section:

In that section it states:

When using a Python virtual environment with mod_wsgi, it is very important that it has been created using the same Python installation that mod_wsgi was originally compiled for. It is not possible to use a Python virtual environment to force mod_wsgi to use a different Python version, or even a different Python installation.

You cannot for example force mod_wsgi to use a Python virtual environment created using Python 3.5 when mod_wsgi was originally compiled for Python 2.7. This is because the Python library for the Python installation it was originally compiled against is linked directly into the mod_wsgi module.

So most likely what is happening is that mod_wsgi is compiled for Python 2.6. You cannot in this case force it to use a Python virtual environment created from Python 2.7. When you do this, you will get the error you see about site module being missing.

You will need to uninstall that mod_wsgi from system packages and install mod_wsgi from source code, compiling it against Python 2.7. The easiest way to do this might be to use the pip install method as described in:

Run pip install to install it in your virtual environment and then follow instructions in section 'Connecting into Apache installation' about configuring Apache to use it.