﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
25203	Document changes to WSGI application loading sequence in 1.7	yscumc	nobody	"After upgrading Django from 1.6 to 1.7, I found that there were some undocumented differences in how the wsgi loading is handled.

I had the following in Django 1.6 in my wsgi.py:

{{{
from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()

# Update DJANGO_SETTINGS_MODULE os env variable from internal Apache env variable, set by ""SetEnv"" in httpd.conf
def application(environ, start_response):
    if 'DJANGO_SETTINGS_MODULE' in environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = environ['DJANGO_SETTINGS_MODULE']

    return _application(environ, start_response)
}}}

This will get the env from the Apache conf and set it before a request to make sure that the proper settings file is loaded.

However, in Django 1.7, this broke because `django.setup()` is now run as part of `django.core.wsgi.get_wsgi_application()` and this causes the settings file to be loaded before the first `application()` call (first request).

Previously, the loading of the settings file seems to happen with the first `application()` call, `django.core.wsgi.get_wsgi_application()()`.


Debugging this was actually more difficult than it seems. I initially just got a 400 BAD REQUEST error after upgrading, with no errors in the logs. It took a long time to realize my my custom settings file wasn't being loaded and so `ALLOWED_HOSTS` weren't being loaded either.

After finding out it was a changed behavior in wsgi loading that was causing the problem, fixing the problem was straightforward, but I recommend updating the documentation with this change in Django 1.7 so that others wouldn't run into this issue.


Here's the fixed version that also works with 1.7 (and earlier) if someone is interested:

{{{
# Update DJANGO_SETTINGS_MODULE os env variable from internal Apache env variable, set by ""SetEnv"" in httpd.conf
def application(environ, start_response):
    if 'DJANGO_SETTINGS_MODULE' in environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = environ['DJANGO_SETTINGS_MODULE']

    # Only attempt to execute get_wsgi_application() once
    if not application._app:
        application._app = get_wsgi_application()

    return application._app(environ, start_response)
application._app = None
}}}
"	Cleanup/optimization	new	Documentation	1.7	Normal		wsgi setup application loading	paul@… jon.dufresne@…	Accepted	0	0	0	0	0	0
