LoginSignup
17
40

More than 3 years have passed since last update.

Python Windows で mod_wsgi を Apache に組み込む方法

Last updated at Posted at 2016-07-25

mod_wsgiのダウンロード

まず、Unofficial Windows Binaries for Python Extension Packagesから、Pythonのアーカイブ形式の一つであるホイールファイル(.whl)をダウンロードする

数種類のファイルが存在するが、ダウンロードしてくるのは

mod_wsgi-[mod_wsgiのバージョン]+ap[apacheのバージョン]vc[Visual Studio compiler のバージョン]-cp[Pythonのバージョン]-cp[Pythonのバージョン]m-win[OSのビット数].whl

と一致するファイル
例えば、以下の様な環境でインストールしようとする場合、

  • Windows 64bit
  • Apache 2.4.x
  • Python 3.5.x
mod_wsgi-4.4.23+ap24vc14-cp35-cp35m-win_amd64.whl

をダウンロードしてくる

mod_wsgiのインストール

mod_wsgiをpipを使ってインストールする

pip install mod_wsgi-4.4.23+ap24vc14-cp35-cp35m-win_amd64.wh

成功すると、Pythonがインストールされているフォルダ配下に、mod_wsgi.soができる

C:/Program Files/Python35/mod_wsgi.so

mod_wsgiをApacheに組み込む

できたmod_wsgi.soをApacheがインストールされているフォルダのmodules配下に置く

C:/Programs/Apache24/modules/mod_wsgi.so

httpd.confに追記する

C:/Programs/Apache24/conf/httpd.conf
// 181行目あたり
LoadModule wsgi_module modules/mod_wsgi.so

さらに、以下のコードを任意の場所に追記する

httpd.conf
WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py
WSGIPythonPath /path/to/mysite.com

<Directory /path/to/mysite.com/mysite>
   <Files wsgi.py>
      Order deny,allow
      Allow from all
   </Files>
</Directory>

virtualenv の中にプロジェクトが依存する Python モジュールをインストールしているなら、 virtualenv の site-packages ディレクトリも Python パスに追加する必要がある
そのためには、 Apache の設定にもう一行追加

httpd.conf
// X.XはPythonのバージョン
WSGIPythonPath /path/to/your/venv/lib/pythonX.X/site-packages

Apacheを再起動する

プロジェクトを作成する

wsgi_modを使うには、プロジェクト内にwsgi.pyが必要
以下のコマンドを実行することで、wsgi.pyが含まれるプロジェクトを生成できる

django-admin startproject [プロジェクト名]

ちなみに、wsgi.pyの中身は以下

wsgi.py
"""
WSGI config for helloworld project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "[プロジェクト名].settings")

application = get_wsgi_application()

おまけ

これでApache + mod_wsgiの環境をWindowsに構築できたが、この構成ではコードの変更が即時反映されない
これを解決する方法として、MaxRequestsPerChildをあえて小さい数にして、Apacheが再起動しやすい環境を作るという手がある
詳しくは、modwsgi - ReloadingSourceCode.wikiを参照されたし

httpd.conf
MaxRequestsPerChild 3
17
40
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
40