pythondjangoapachewsgisetenv

Having trouble reading Apache config variable trough wsgi in Django 1.11


I'm trying to read database settings from the Apache config and getting error. I tried many solutions from other questions, but it looks like this may be the Django 1.11 version issue.

This is what I have.

In httpd.conf:

<VirtualHost *:80>
    ....

    SetEnv DB_NAME XYZ
    SetEnv DB_USER abc

    ....
</VirtualHost>

In wsgi.py:

import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..'))

sys.path.append(PROJECT_DIR)

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

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

env_variables_to_pass = ['DB_NAME', 'DB_USER', ]

def application(environ, start_response):
  for var in env_variables_to_pass:
    os.environ[var] = environ.get(var, '')
  return _application(environ, start_response)

In settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],

         ......
        },
    }

And when I run my application, I'm getting 'Internal Server Error'.

This is what in the apache_error.log:

[wsgi:error] raise KeyError(key) from None\r
[wsgi:error] KeyError: 'DB_NAME'\r

}


Solution

  • SetEnv only sets the per request WSGI environ dictionary values, not process wide environment variables. You would need to set the process environment variables from the wsgi.py file, or from a Python code file or config file processed as a side effect of importing the wsgi.py file the first time.

    The only place in system configuration for Apache where you can set process wide environment variables is in a envvars file, but not all Apache distributions on Linux system support that. It is also not recommended as it sets them for the whole of Apache and not individual applications running under Apache.