mod_wsgiでアプリごとにvirtualenv環境を設定する

環境は以下。

flaskでやってみます。

前準備

まずpythonbrewでvirtualenvで環境をつくる。

$ pybrew venv create -p 2.7.2 --no-site-packages test
$ pybrew venv use -p 2.7.2 test
(test)$ pip install flask

適当にアプリを置く。
~/app/test/app.wsgi

import sys, os
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

from main import app as application

~/app/test/main.py

# -*- coding: utf-8 -*-

from flask import Flask

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/')
def index():
    return 'test'

if __name__ == '__main__':
    app.run()

mod_wsgiはpythonbrewで入れたpython2.7.2でコンパイル、インストールする。

...
$ ./configure --with-apxs=/usr/bin/apxs2 --with-python=/home/あなた様/.pythonbrew/pythons/Python-2.7.2/bin/python
...

apacheの設定

WSGIPythonHomeにmod_wsgiのインストールに使ったpythonを指定する。

/etc/apache2/conf.d/wsgi.conf

LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
WSGIPythonHome /home/あなた様/.pythonbrew/pythons/Python-2.7.2
WSGIPythonEggs /var/www/.python-eggs
WSGISocketPrefix /var/run/wsgi

/etc/apache2/sites-available/default

...
    WSGIDaemonProcess test user=あなた様 group=あなた様 threads=5 python-path=/home/あなた様/.pythonbrew/venvs/Python-2.7.2/test/lib/python2.7/site-packages
    WSGIScriptAlias /test /home/あなた様/app/test/app.wsgi
    <Directory "/home/あなた様/app/test">
        WSGIProcessGroup test
        WSGIApplicationGroup %{GLOBAL}
        Options ExecCGI
   </Directory>
...


wsgiに使うpythonはインストール時に固定する必要がありますが、site-packagesはWSGIDaemonProcessに指定することでアプリごとに設定することができます。