mod_wsgi (Apache)

もしApacheウェブサーバを使っているときは、mod_wsgiを使うことを検討してください。 If you are using the `Apache`_ webserver, consider using `mod_wsgi`_.

注意 Watch Out

予め自分のアプリケーションのファイル内にあるかもしれない全てのapp.run()呼び出しは、if __name__ == '__main__':ブロックの内側にあるか、別のファイルに移動していることを確実にしておいてください。mod_wsgiへアプリケーションをデプロイするときは望まないローカルWSGIサーバを常に開始してしまうために、app.run()が呼び出されないことを、まずは確認してください。 Please make sure in advance that any ``app.run()`` calls you might have in your application file are inside an ``if __name__ == '__main__':`` block or moved to a separate file. Just make sure it's not called because this will always start a local WSGI server which we do not want if we deploy that application to mod_wsgi.

mod_wsgiのインストール Installing `mod_wsgi`

もしmod_wsgiをまだインストールしていない場合、package managerを使ってインストールするか自分でコンパイルしてください。mod_wsgiのinstallation instructionsはUNIXシステム上でのソースのインストールをカバーします。 If you don't have `mod_wsgi` installed yet you have to either install it using a package manager or compile it yourself. The mod_wsgi `installation instructions`_ cover source installations on UNIX systems.

もしUnbuntu/Debianを使っている場合、apt-getすることが可能で、以下のようにして有効にできます: If you are using Ubuntu/Debian you can apt-get it and activate it as follows:

$ apt-get install libapache2-mod-wsgi-py3

もしyumベースのディストリビューション(Fedora, OpenSUSEなど)を使っている場合、以下のようにインストール可能です: If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you can install it as follows:

$ yum install mod_wsgi

FreeBSDではmod_wsgiのインストールにwww/mod_wsgiのportをコンパイルするかpkg_addを使います: On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by using pkg_add:

$ pkg install ap24-py37-mod_wsgi

もしpkgsrcを使っている場合、mod_wsgiのインストールにwww/ap2-wsgiパッケージをコンパイルします。 If you are using pkgsrc you can install `mod_wsgi` by compiling the `www/ap2-wsgi` package.

もし最初にapacheを再読み込みしたとき子プロセスのsegfaultingに出くわした場合それらを安全に無視できます。ただサーバを再スタートしてください。 If you encounter segfaulting child processes after the first apache reload you can safely ignore them. Just restart the server.

.wsgiファイルの作成 Creating a `.wsgi` file

アプリケーションを実行するためにはyourapplication.wsgiファイルが必要です。このファイルは、mod_wsgiが開始時にアプリケーションのオブジェクトを取得するために使うコードを含みます。そのファイルの中でapplicationと呼ばれるオブジェクトがアプリケーションとして使用されます。 To run your application you need a :file:`yourapplication.wsgi` file. This file contains the code `mod_wsgi` is executing on startup to get the application object. The object called `application` in that file is then used as application.

殆どのアプリケーションでは以下のファイルで十分なはずです: For most applications the following file should be sufficient::

from yourapplication import app as application

__init__.pyファイルの中でfactory関数が使用されている場合、関数がimportされるはずです: If a factory function is used in a :file:`__init__.py` file, then the function should be imported::

from yourapplication import create_app
application = create_app()

アプリケーション作成用のfactory関数を使わずに単一の(singleton)インスタンスを使う場合、そのインスタンスをapplicationとして直接importできます。 If you don't have a factory function for application creation but a singleton instance you can directly import that one as `application`.

もう一度見つけ出せるどこか(例: /var/www/yourapplication)へそのファイルを格納し、yourapplicationと使用するすべてのライブラリがpythonのload pathにあることを確実にしてください。もしシステム全体用(system wide)にインストールしたくない場合、virtual pythonインスタンスの使用を検討してください。(その場合)実際に自分のアプリケーションをvirtualenvへさらにインストールすることを覚えておいてください。代わりに、importする前に.wsgiファイル中のpathをpatchするだけという選択肢があります: Store that file somewhere that you will find it again (e.g.: :file:`/var/www/yourapplication`) and make sure that `yourapplication` and all the libraries that are in use are on the python load path. If you don't want to install it system wide consider using a `virtual python`_ instance. Keep in mind that you will have to actually install your application into the virtualenv as well. Alternatively there is the option to just patch the path in the ``.wsgi`` file before the import::

import sys
sys.path.insert(0, '/path/to/the/application')

Apacheの設定 Configuring Apache

しなければいけない最後のことは、自分のアプリケーション用にApacheの設定ファイルを作成することです。以下の例ではmod_wsgiにセキュリティ上の理由から違うユーザとしてアプリケーションを実行するよう伝えています: The last thing you have to do is to create an Apache configuration file for your application. In this example we are telling `mod_wsgi` to execute the application under a different user for security reasons:

<VirtualHost *>
    ServerName example.com

    WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5
    WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi

    <Directory /var/www/yourapplication>
        WSGIProcessGroup yourapplication
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

注目: WSGIDaemonProcess はWindowsでは未実装であり、Apacheは上記の設定での実行を拒否します。Windowsシステム上では、それらの行を消去してください: Note: WSGIDaemonProcess isn't implemented in Windows and Apache will refuse to run with the above configuration. On a Windows system, eliminate those lines:

<VirtualHost *>
    ServerName example.com
    WSGIScriptAlias / C:\yourdir\yourapp.wsgi
    <Directory C:\yourdir>
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

注目: Apache 2.4ではアクセス制御の設定にいくらか変更がありました。 Note: There have been some changes in access control configuration for `Apache 2.4`_.

最も目立つのは、ディレクトリのアクセス権の文法の変更です。以下のhttpd 2.2用から Most notably, the syntax for directory permissions has changed from httpd 2.2

Order allow,deny
Allow from all

こちらのhttpd 2.4文法になりました to httpd 2.4 syntax

Require all granted

さらなる情報はmod_wsgi documentationを調べてください。 For more information consult the `mod_wsgi documentation`_.

Troubleshooting

もし自分のアプリケーションが走らないとき、トラブル対応のために以下のガイドに従ってください: If your application does not run, follow this guide to troubleshoot:

問題:アプリケーションが走らず、エラーログは無視されたSystemExitを示しています **Problem:** application does not run, errorlog shows SystemExit ignored

if __name__ == '__main__':条件でガードされていないapp.run()呼び出しがアプリケーションのファイルにあります。そのrun()呼び出しをファイルから消去するか、示したようなifブロックの内側に押し入れます。 You have an ``app.run()`` call in your application file that is not guarded by an ``if __name__ == '__main__':`` condition. Either remove that :meth:`~flask.Flask.run` call from the file and move it into a separate :file:`run.py` file or put it into such an if block.

問題アプリケーションがpermission errors(権限エラー)を出します **Problem:** application gives permission errors

おそらく自分のアプリケーションを正しくないユーザで走らせているのが原因です。アプリケーションがアクセスする必要があるフォルダに適切な権限を設定し、アプリケーションを正しいユーザ((Apache設定での)WSGIDaemonProcessディレクティブのusergroupのパラメータ)で走らせることを確実にしてください。 Probably caused by your application running as the wrong user. Make sure the folders the application needs access to have the proper privileges set and the application runs as the correct user (``user`` and ``group`` parameter to the `WSGIDaemonProcess` directive)

問題アプリケーションがエラーを表示して死にます **Problem:** application dies with an error on print

mod_wsgiはsys.stdoutsys.stderrへのあらゆる操作を認めないことを忘れないでください。この保護はWSGIRestrictStdoutoffにすることで無効にできます: Keep in mind that mod_wsgi disallows doing anything with :data:`sys.stdout` and :data:`sys.stderr`. You can disable this protection from the config by setting the `WSGIRestrictStdout` to ``off``:

WSGIRestrictStdout Off

代わりに.wsgiファイルの中で標準出力を別のストリームへ置き換えることも可能です: Alternatively you can also replace the standard out in the .wsgi file with a different stream::

import sys
sys.stdout = sys.stderr
問題リソースへアクセスするとIOエラーを出します **Problem:** accessing resources gives IO errors

おそらくアプリケーションがsite-packageフォルダの中へシンボリックリンクした(symlinked)単一の.pyファイルです。これは機能しないことを意識し、代わりにファイルが格納されているフォルダをpythonpathに押し入れるか、アプリケーションをパッケージへ変換してください。 Your application probably is a single .py file you symlinked into the site-packages folder. Please be aware that this does not work, instead you either have to put the folder into the pythonpath the file is stored in, or convert your application into a package.

この理由は、インストールされていないパッケージでは、モジュールのファイル名がリソースの場所に使用され、シンボリックリンクにより誤ったファイル名が拾われてしまうためです。 The reason for this is that for non-installed packages, the module filename is used to locate the resources and for symlinks the wrong filename is picked up.

自動リロードのサポート Support for Automatic Reloading

デプロイのツールを手助けするために自動リロードのサポートを有効にできます。いつでも.wsgiファイルに何か変更があったときは、mod_wsgiはすべてのデーモンプロセスを再読み込み(reload)します。 To help deployment tools you can activate support for automatic reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will reload all the daemon processes for us.

そのためには、ただ以下のディレクティブを自分のDirectoryセクションへ追加します: For that, just add the following directive to your `Directory` section:

WSGIScriptReloading On

Virtual Environmentを使った作業 Working with Virtual Environments

virtual environmentは必要な依存対象をシステム全体用にインストールしないので、どこで何が使われるかについてよりよく制御できるという利点があります。もしvirtual environmentをmod_wsgiと一緒に使いたい場合、.wsgiファイルを少し変更する必要があります。 Virtual environments have the advantage that they never install the required dependencies system wide so you have a better control over what is used where. If you want to use a virtual environment with mod_wsgi you have to modify your ``.wsgi`` file slightly.

.wsgiファイルの最上部に以下の行を追加してください: Add the following lines to the top of your ``.wsgi`` file::

activate_this = '/path/to/env/bin/activate_this.py'
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this))

これはロード用のpathをvirtual environmentの設定に沿って設定します。pathは絶対パスにする必要があることを忘れないでください。 This sets up the load paths according to the settings of the virtual environment. Keep in mind that the path has to be absolute.