如何使用 WSGI 进行部署Link to this heading
Django 的主要部署平台是 WSGI,它是 Web 服务器和 Web 应用的 Python 标准。
Django's startproject management command sets up a minimal default
WSGI configuration for you, which you can tweak as needed for your project,
and direct any WSGI-compliant application server to use.
Django 提供了下面这些 WSGI 服务的入门文档:
application 对象Link to this heading
用 WSGI 部署的关键是 application callable,应用服务器用它与你的代码交互。 application callable 一般以一个位于 Python 模块中,名为 application 的对象的形式提供,且对服务器可见。
startproject 命令创建了文件 <project_name>/wsgi.py,其中包含了 application callable。
Django 开发服务器和生产环境的 WSGI 部署都用到了它。
WSGI 服务器从其配置中获取 application callable 的路径。Django 的默认服务器( runserver 命令),从配置项 WSGI_APPLICATION 中获取。默认值是 <project_name>.wsgi.application,指向 <project_name>/wsgi.py 中的 application callable。
配置 settings 模块Link to this heading
当 WSGI 服务器加载应用时,Django 需要导入配置模块——完整定义应用的地方。
Django 利用 DJANGO_SETTINGS_MODULE 环境变量来定位合适的配置模块。它必须包含到配置模块的点式路径。开发环境和生产环境可以配置不同值;这都取决于你是如何组织配置的。
若未设置该变量, wsgi.py 默认将其设置为 mysite.settings, mysite 即工程名字。这就是 runserver 默认的发现默认配置行为。
应用 WSGI 中间件Link to this heading
To apply WSGI middleware you can wrap the application object. For instance
you could add these lines at the bottom of wsgi.py:
from helloworld.wsgi import HelloWorldApplication
application = HelloWorldApplication(application)
如果你想将 Django 应用于一个 WSGI 应用或其它框架联合起来,可以用自定义 WSGI 应用替换 Django 的 WSGI 应用,前者会在稍晚时候将任务委托给 WSGI 应用。