J

Mac OS X 10.6.8 に mod_wsgi を入れて,python で Web ページを作成する

Mac OS X 10.6.8 で Web ページを python によって作成したい.
そのために,mod_wsgi というモジュールを apache2 に組み込む方法を書く.

ほとんど Homebrew で mod_wsgi のインストール の引用です.

システム要件
-Intel CPU 搭載
-0.5 Leopard か、それ以上の OS
-X11 含む Xcode (OS インストールディスクから入手)
-Java Developer Update

1. homebrew のインストール

まずは Java のバージョンを確認.

$ java -version

java version 1.6.0_22 だったらアップデートを(たぶん Mac OS のアップデートで自動更新されるはず).
続いて,homebrew のインストール.

$ ruby -e "$(curl -fsSL https://gist.github.com/raw/323731/install_homebrew.rb)"
==> This script will install:
/usr/local/bin/brew
/usr/local/Library/Formula/...

..(中略: 途中でパスワードを入力)..

local/share/man /usr/local/share/man/man1
==> Downloading and Installing Homebrew...
==> Installation successful!

homebrew のバージョンを確認しておく.

$ brew -v
0.8

config の確認は次のコマンド

$ brew --config

2. mod_wsgi のインストール

homebrew を使って mod_wsgi をインストール.

$ brew tap homebrew/apache
$ brew install mod_wsgi

ずらずらと文字が出て,20秒ぐらいで終わる.
次に,mod_wsgi のリンクを apache に設定.

$ ln -s /usr/local/Cellar/mod_wsgi/3.3/libexec/mod_wsgi.so /usr/libexec/apache2/

3. apache の設定

apache の設定ファイル,httpd.conf を編集.

$ sudo vi /etc/apache2/httpd.conf
...
# LoadModuleが書いてある部分に一行追加
LoadModule wsgi_module  libexec/apache2/mod_wsgi.so
...
...
WSGIScriptAlias /wsgi /Users/(ユーザ名)/Sites/test.py

/wsgi および test.py は自分の好きな名前にして良い.
apache を再起動

$ sudo apachectl restart

ログで,mod_wsgi の動作を確認

$ tail -f /var/log/apache2/error_log 
...
...
[Thu Jun 30 18:17:43 2011] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 mod_wsgi/3.0c4 Python/2.6.1 configured -- resuming normal operations

Cntl + C で tail コマンドを終了.

4. アプリケーション作成

サンプルファイルを作成.

$ vi ~/Sites/test.py
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World! using mod_wsgi!!!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

http://localhost/wsgi/にアクセス."Hello World! using mod_wsgi!!!"と表示されれば成功.

===追記===
httpd.conf で WSGIScriptAlias /wsgi /Users/(ユーザ名)/Sites/wsgi/test.py としておいたほうが管理がしやすい.
http://localhost/wsgihttp://localhost/wsgi/test.py と指定できるようになる.
wsgi ディレクトリ内に他のファイルを作成し,直接アクセスもできるようだ.