Set up the Django settings file via DJANGO_SETTING

2019-04-08 12:08发布

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.

2条回答
Fickle 薄情
2楼-- · 2019-04-08 12:22

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
查看更多
相关推荐>>
3楼-- · 2019-04-08 12:42

To achieve that, you can use the following code in your application's wsgi.py file :

import os
from django.core.wsgi import get_wsgi_application

def application(environ, start_response):
    _application = get_wsgi_application()
    os.environ['DJANGO_SETTINGS_MODULE'] = environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
    return _application(environ, start_response)

Tip: don't forget to customize the myapp.settings string to match your default settings module.

查看更多
登录 后发表回答