Considerations for Apache2's mod_wsgi configuration

Hi all,

Software of the system:

  • Debian: 12.1
  • Python3: 3.11.2
  • Python3-venv: 3.11.2-1+b1
  • Django: 4.2.4
  • Apache2: 2.4.57-2
  • Lib-apache2-mod-wsgi-py3: 4.9.4-1+b2

I’ve been following the quick started guide to create the poll’s app and then I created my own app susceffully. Following the Django docs¹, when I published the code using mod_wsgi for Apache, I received this error:

[Wed Aug 30 01:06:53.821691 2023] [wsgi:warn] [pid 6137:tid 140391512356736] (13)Permission denied: mod_wsgi (pid=6137): Unable to stat Python home /home/user/django_app/django. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path.
Python path configuration:
PYTHONHOME = ‘/home/user/django_app/django’
PYTHONPATH = (not set)
program name = ‘python3’
isolated = 0
environment = 1
user site = 1
safe_path = 0
import site = 1
is in build tree = 0
stdlib dir = ‘/home/user/django_app/django/lib/python3.11’
sys._base_executable = ‘/usr/bin/python3’
sys.base_prefix = ‘/home/user/django_app/django’
sys.base_exec_prefix = ‘/home/user/django_app/django’
sys.platlibdir = ‘lib’
sys.executable = ‘/usr/bin/python3’
sys.prefix = ‘/home/user/django_app/django’
sys.exec_prefix = ‘/home/user/django_app/django’
sys.path = [
‘/home/user/django_app/django/lib/python311.zip’,
‘/home/user/django_app/django/lib/python3.11’,
‘/home/user/django_app/django/lib/python3.11/lib-dynload’,
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named ‘encodings’
Current thread 0x00007faf72393780 (most recent call first):

Googling this error, always recomended change permissions of the parent directory²³… In my tests, I use the home directory of a non-privileged user but not all people used it⁴… I think may be a security risk and it’s not clear into documentation.

I don’t known if there are other better solutions but that is the way I solved the problem in a fresh migration. As root:

  • Create parent directory: mkdir /opt/djangp_app
  • Create python virtual enviroment: python -m venv --system-site-packages /opt/django_app/django
  • Copy Django App into /opt/django_app. Ex: /opt/django_app/polls
  • Change permissions to www-data: chown -R www-data:www-data /opt/django_app

Thats it’s a little summary for install/migrate a Django app without permissions errors with mod_wsgi for Apache2.

Kind regards, Fernando.

  1. How to use Django with Apache and mod_wsgi | Django documentation | Django
  2. 403 Forbidden-Apache2, You don't have permission to access this resource - #4 by howa003
  3. django - mod_wsgi - Permission denied - Unable to stat Python home - Stack Overflow
  4. server - apache2 Ubuntu django : can't upload my django app - Ask Ubuntu