[python] Target WSGI script cannot be loaded as Python module

I am trying to deploy mod_wsgi with apache to run a django application but I am getting an error 500 internal server error The apache logs shows:

[Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64] mod_wsgi (pid=16142): Exception occurred processing WSGI script '/home/user/bms/apache/django.wsgi'.
[Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64] Traceback (most recent call last):
[Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64]   File "/home/user/bms/apache/django.wsgi", line 13, in <module>
[Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64]     import django.core.handlers.wsgi
[Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64] ImportError: No module named django.core.handlers.wsgi

My apache virtual host is as follows:

<VirtualHost *:80>

    DocumentRoot /home/user/bms

    <Directory /home/user/bms>
        Order allow,deny
        Allow from all
    </Directory>

WSGIDaemonProcess bms user=user group=user processes=2 threads=25 python-path=/usr/local/lib/python2.7/site-packages


    WSGIProcessGroup bms

    WSGIScriptAlias / /home/user/bms/apache/django.wsgi

</VirtualHost>

And the referenced wsgi file in my app directory with 0777 permissions:

import os
import sys

path = '/home/user/bms'
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'bms.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

I heard that this may be because the apache user does not have the correct permissions. However I have no idea how to fix this. I also tried starting the deamon with the www-data user and this did not solve the issue.

EDIT:

I solved this by copying the virtual hosts file into the default one and then disabling the old one with a2dissite. I have no idea how I can do it "properly" and set it so apache goes to the virtual host I want it to though.

This question is related to python django apache mod-wsgi wsgi

The answer is


I had the same error

Target WSGI script cannot be loaded as Python module

This was because the python path was not added in the apache.conf

Depending on the Apache and Ubuntu version you need to update the apache.conf or httpd.conf file with the pythonWSGIPath

In my case I need to edit the apache.conf

sudo nano /etc/apache2/apache2.conf

Then add the following line at the end (Change the my_project to the project your project name)

WSGIPythonPath /var/www/my_project

And everything works with charm


In my own case on windows in xampp, I was incorrectly loading the application path in the wsgi.py file like so:

Incorrect:

import sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "advisory_portal.settings")

application = get_wsgi_application()
sys.path.append('C:/xampp/htdocs/advisory_portal/advisory_portal')
sys.path.append('C:/xampp/htdocs/advisory_portal')

Instead of:

Correct:

import sys

sys.path.append('C:/xampp/htdocs/advisory_portal/advisory_portal')
sys.path.append('C:/xampp/htdocs/advisory_portal')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "advisory_portal.settings")

application = get_wsgi_application()

Don't forget to import sys python package


As this question became sort of a pool for collecting solutions for problems that result in the error giving this question its title, I'd like to add this one, too.

In my case, I want to run OpenStack Keystone (Ocata) using Apache and WSGI on Ubuntu 16.04.2. The processes start but as soon as I query keystone I get

mod_wsgi (pid=20103): Target WSGI script '/opt/openstack/bin/keystone-wsgi-public' cannot be loaded as Python module.

I had two vhosts, one had

WSGIDaemonProcess keystone-public ...
WSGIProcessGroup keystone-public ...

while the other had

WSGIDaemonProcess keystone-admin ...
WSGIProcessGroup keystone-admin ...

I solved the problem by renaming them. The vhost entries now read:

WSGIDaemonProcess kst-pub ...
WSGIProcessGroup kst-pub ...

and

WSGIDaemonProcess kst-adm ...
WSGIProcessGroup kst-adm ...

I didn't investigate any further. Solved as works for me.


For me the issue was that the WSGI script wasn't executable.

sudo chmod a+x django.wsgi

or just

sudo chmod u+x django.wsgi

so long as you have the correct owner


I know this question is pretty old, but I wrestled with this for about eight hours just now. If you have a system with SELinux enabled and you've put your virtualenv in particular places, mod_wsgi won't be able to add your specified python-path to the site-packages. It also won't raise any errors; as it turns out the mechanism it uses to add the specified python-path to the site packages is with the Python site module, specifically site.adduserdir(). This method doesn't raise any errors if the directory is missing or can't be accessed, so mod_wsgi also doesn't raise any errors.

Anyway, try turning off SELinux with

sudo setenforce 0

or by making sure that the process you're running Apache as has the appropriate ACLs with SELinux to access the directory the virtualenv is in.


I was getting this error. I'm using python 3 in a virtual environment found this in my apache logs

[Fri Dec 21 08:01:43.471561 2018] [mpm_prefork:notice] [pid 21786] AH00163: Apache/2.4.6 (Red Hat Enterprise Linux) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations

I had installed wsgi using yum -y install mod_wsgi. This had installed mod_wsgi compiled for python 2. So I uninstalled it

yum remove mod_wsgi

and installed mod_wsgi compiled for python 3 using

yum install python35u-mod_wsgi

It worked after that


I had a similar problem with this error message in the logs:

Target WSGI script '/home/web2py/wsgihandler.py' cannot be loaded as Python module.

The solution was the deletion of an incorrect WSGIPythonHome directive (pointing to the application directory) from /etc/httpd/conf.d/wsgi.conf

I'm on RedHat using CentOS repositories.

Recommend following Graham Dumpleton's installation/configuration instructions. Testing configuration against the helloworld application showed me that mod_wsgi was working and the configuration was at fault.

However, the error message gave little clue as to what was wrong.


Did you try it without the WSGIDaemonProcess option?

I had no trouble setting up mod_wsgi at home, but did it without the daemon option. You mentioned solving by moving around virtual hosts files and I note this caveat in the docs for WSGIDaemonProcess:

Also note that the name of the daemon process group must be unique for the whole server. That is, it is not possible to use the same daemon process group name in different virtual hosts.

Don't know if that's coincidence.


Sometimes when I get stuck on this I hard code a path to project in the wsgi file like:

import os
import sys


sys.path.append("/var/www/html/myproject")
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

application = get_wsgi_application()

Adding on to the list this is how I got it working.

I was trying to install CKAN 2.7.2 on CentOS 7 from source and kept coming up against this error. For me it was because SELinux was enabled. I didn't need to disable it. Instead, after reading https://www.endpoint.com/blog/2010/10/13/selinux-httpd-modwsgi-26-rhel-centos-5, I found that turning on httpd_can_network_connect fixed it:

setsebool -P httpd_can_network_connect on

From that page:

httpd_can_network_connect - Allows httpd to make network connections, including the local ones you'll be making to a database


I recommend trying to downgrade DJANGO to version 2.1.1.


The solution that finally worked for me, after trying many of these options unsuccessfully was simple, but elusive because I struggled to figure out what actual paths to use.

I created a mezzanine project, which is based on django, with the following commands. I list them here to make the paths explicit.

/var/www/mysite$ python3 -m venv ./venv
/var/www/mysite$ source ./venv/bin/activate
(venv) /var/www/mysite$ mezzanine-project mysite
(venv) /var/www/mysite$ cd mysite
(venv) /var/www/mysite/mysite$

Now, the path to the wsgi.py file is:

/var/www/mysite/mysite/mysite/wsgi.py

The directives that worked for this installation within my /etc/apache2/sites-available/mysite.conf file follow:

...<VirtualHost...>
    ...
    WSGIDaemonProcess mysite python-home=/var/www/mysite/venv python-path=/var/www/mysite/mysite
    WSGIProcessGroup mysite
    WSGIScriptAlias / /var/www/mysite/mysite/mysite/wsgi.py process-group=accounting
    <Directory /var/www/mysite/mysite/mysite>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>
    ...
</VirtualHost>...

I tried numerous versions of python-home and python-path and got the OP's error repeatedly. Using the correct paths here should also accomplish the same things as @Dev's answer without having to add paths in the wsgi.py file (supplied by mezzanine, and no editing necessary in my case).


I had the same problem and at first I didn't realise I could scroll further down and see the actual error message. In my case, it was an import error:

ImportError: No module named bootstrap3

After installing it via pip (pip install django-bootstrap3), I restarted Apache and it worked.


I had the same problem and it got solved using

sudo easy_install cx_Oracle

but remember to unistall cx_oracle before installing it using easy_install.

Command to uninstall: pip uninstall cx_oracle


Appending path in wsgi.py is the direction, but instead of appending django appending path sys.path.append("/path/to/virtual/environment/lib/pythonX.X/site-packages") fixed my case.

This is for a django project using python2.7 on ubuntu 16.04.


I had similar issue eg apache log error "wsgi.py cannot be loaded as Python module."

It turned out I had to stop and then start apache instead of just restarting it.


If you install your project’s Python dependencies inside a virtualenv, you’ll need to add the path to this virtualenv’s directory to your Python path as well. To do this, add an additional path to your WSGIPythonPath directive, with multiple paths separated by a colon (:) if using a UNIX-like system, or a semicolon (;) if using Windows


For me the problem was wsgi python version mismatch. I was using python 3, so:

$ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi
$ sudo apt-get install libapache2-mod-wsgi-py3

Warning from @alxs before you copy/paste these commands:
If there are python 2 projects running on the server that use wsgi and apache, the above commands will effectively shut them down.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to apache

Enable PHP Apache2 Switch php versions on commandline ubuntu 16.04 Laravel: PDOException: could not find driver How to deploy a React App on Apache web server Apache POI error loading XSSFWorkbook class How to enable directory listing in apache web server Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to enable php7 module in apache? java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

Examples related to mod-wsgi

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything "make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi) Target WSGI script cannot be loaded as Python module How to install python developer package? Difference between socket and websocket?

Examples related to wsgi

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything How many concurrent requests does a single Flask process receive? Target WSGI script cannot be loaded as Python module 104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?