Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up the Django settings file via DJANGO_SETTINGS_MODULE environment variable with Apache WSGI

How to change the settings file used by Django when launched by Apache WSGI only with DJANGO_SETTINGS_MODULE environment variable ?

The Django documentation shows how-to achieve this with a different WSGI application file but if we don't want to create a dedicated WSGI file as well as a dedicated settings file for our different environments, using only environment variable DJANGO_SETTINGS_MODULE in Apache with SetEnv is not sufficent.

The variable is indeed passed to application call in environ variable but as the django.conf retrieve the settings like this :

settings_module = os.environ[ENVIRONMENT_VARIABLE]

it never see the right variable.

like image 526
gyzpunk Avatar asked Aug 25 '14 15:08

gyzpunk


1 Answers

As only one instance of a Django application can be run within the context of a Python sub interpreter, the best way of doing things with mod_wsgi would be to dedicate each distinct Django site requiring a different settings, to a different mod_wsgi daemon process group.

In doing that, use a name for the mod_wsgi daemon process group which reflects the name of the settings file which should be used and then at global scope within the WSGI script file, set DJANGO_SETTINGS_MODULE based on the name of the mod_wsgi daemon process group.

The Apache configuration would therefore have something like:

WSGIDaemonProcess mysite.settings_1
WSGIDaemonProcess mysite.settings_2

WSGIScriptAlias /suburl process-group=mysite.settings_2 application-group=%{GLOBAL}
WSGIScriptAlias / process-group=mysite.settings_1 application-group=%{GLOBAL}

and the WSGI script file:

import os
try:
    from mod_wsgi import process_group
except ImportError:
    settings_module = 'mysite.settings'
else:
    settings_module = process_group

os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
like image 109
Graham Dumpleton Avatar answered Oct 06 '22 00:10

Graham Dumpleton