Redhat – Python module import from a WSGI script fails on RedHat server

apache-2.4mod-wsgipythonredhatwsgi

Here is a minimal WSGI script, importing a custom python module.

It runs fine on a development environment (Mint 18.1, Apache 2.4.18, libapache2-mod-wsgi-py3), but fails when deployed to a test server (RHEL 8.0, Httpd/Apache 2.4.37, python3-mod_wsgi).

Here is the apache config block:

<VirtualHost *:80>
      ServerName localhost
      ServerAdmin admin@localhost
      WSGIDaemonProcess MyApp
      WSGIProcessGroup MyApp
      WSGIScriptAlias /test /var/www/wsgi/wsgiapp.wsgi
      <Directory /var/www/wsgi/>
         Require all granted
      </Directory>
      LogLevel warn
</VirtualHost>

The WSGI script (/var/www/wsgi/wsgiapp.wsgi):

#!/usr/bin/python3
import sys 
path = '/srv/git/myproject/mymodule/'
if path not in str(sys.path):
   sys.path.insert(0, path)
from hellofunc import hello as application

The file to be imported (/srv/git/myproject/mymodule/hellofunc.py):

def hello(environ, start_response):
   start_response('200 OK', [('Content-type', 'text/plain'),('Content-Length','6')])
   return [b'Hello']

The Apache error log on the RedHat server:

mod_wsgi (pid=1060): Failed to exec Python script file
'/var/www/wsgi/wsgiapp.wsgi'. mod_wsgi (pid=1060): Exception occurred
processing WSGI script '/var/www/wsgi/wsgiapp.wsgi'. Traceback (most
recent call last): File "/var/www/wsgi/wsgiapp.wsgi", line 7, in

from hellofunc import hello as application ModuleNotFoundError: No module named 'hellofunc'

The file permissions have been arranged so that the apache/www-data groups can read/execute the files on each server.
Only distro packages have been used. Nothing built from source, nor installed through Python pip.

Best Answer

The RedHat server had SELinux enabled by default. Confirmed by setting permissive mode:

# setenforce 0

EDIT: SELinux settings

Set the python files security context to be reachable by HTTPD:

# chcon -R --type=httpd_sys_content_t /srv/git/myproject/

Alternately, if the python files are under $HOME, you can the SELinux booleans to let HTTPD access them:

# setsebool -P httpd_enable_homedirs on
Related Topic