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

对着背影说爱祢 提交于 2019-12-06 04:41:55

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/25489009/set-up-the-django-settings-file-via-django-settings-module-environment-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!