WSGI とともにデプロイするには¶
Django の主要なデプロイプラットフォームは、 Web サーバと Web アプリケーション に関して Python の標準である WSGI です。
Django の startproject
管理用コマンドはシンプルなデフォルトの WSGI 設定をセットアップします。必要に応じて、あなたのプロジェクトと WSGI 準拠の Web サーバに合わせて微調整することができます。
Django には以下の WSGI サーバのために、手引きとなるドキュメントが用意されています:
The application
object¶
WSGI デプロイでキーとなる概念は、Web サーバがあなたのコードと通信するために使う application
という呼び出し可能オブジェクトです。これは一般的に、サーバにアクセスできる Python モジュールの中で application
という名前のオブジェクトとして提供されています。
startproject
コマンドは、この application
呼び出し可能オブジェクトを含む <project_name>/wsgi.py
ファイルを生成します。
これは、Django のデプロイサーバーによって、また WSGI デプロイプロダクションにおいて、これら両方で使われます。
WSGI サーバーは application
呼び出し可能オブジェクトへのパスを、その設定から取得します。Django のビルトインサーバー (要するに runserver
コマンド) は、WSGI_APPLICATION
の設定からこれを読み出します。デフォルトでは、 <project_name>/wsgi.py
内の application
呼び出し可能オブジェクトを指す ``<project_name>.wsgi.application` がセットされています。
設定モジュールを設定する¶
WSGI サーバがあなたのアプリケーションを読み込むとき、Django は設定モジュールをインポートする必要があります。そのモジュールは、あなたのあなたのアプリケーション全体が定義されている場所です。
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.settings
, where 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
enforcing os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
in
your wsgi.py
.
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 wsgi.py
:
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. In those cases the
request_finished
signal isn’t sent. This can
result in idle connections to database and memcache servers.