How to deploy with WSGI¶
Django’s primary deployment platform is WSGI, the Python standard for web servers and applications.
startproject management command sets up a simple default
WSGI configuration for you, which you can tweak as needed for your project,
and direct any WSGI-compliant application server to use.
Django includes getting-started documentation for the following WSGI servers:
The key concept of deploying with WSGI is the
application callable which
the application server uses to communicate with your code. It’s commonly
provided as an object named
application in a Python module accessible to
startproject command creates a file
<project_name>/wsgi.py that contains such an
It’s used both by Django’s development server and in production WSGI deployments.
WSGI servers obtain the path to the
application callable from their
configuration. Django’s built-in servers, namely the
runfcgi commands, read it from the
setting. By default, it’s set to
points to the
application callable in
Configuring the settings module¶
When the WSGI server loads your application, Django needs to import the settings module — that’s where your entire application is defined.
Django uses the
DJANGO_SETTINGS_MODULE environment variable to
locate the appropriate settings module. It must contain the dotted path to the
settings module. You can use a different value for development and production;
it all depends on how you organize your settings.
If this variable isn’t set, the default
wsgi.py sets it to
mysite is the name of your project. That’s how
runserver discovers the default settings file by default.
Since environment variables are process-wide, this doesn’t work when you run multiple Django sites in the same process. This happens with mod_wsgi.
To avoid this problem, use mod_wsgi’s daemon mode with each site in its
own daemon process, or override the value from the environment by
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" in
Applying WSGI middleware¶
To apply WSGI middleware you can simply wrap the application object. For
instance you could add these lines at the bottom of
from helloworld.wsgi import HelloWorldApplication application = HelloWorldApplication(application)
You could also replace the Django WSGI application with a custom WSGI application that later delegates to the Django WSGI application, if you want to combine a Django application with a WSGI application of another framework.
Some third-party WSGI middleware do not call
close on the response
object after handling a request — most notably Sentry’s error reporting
middleware up to version 2.0.7. In those cases the
request_finished signal isn’t sent. This can
result in idle connections to database and memcache servers.