LoginSignup
43
38

More than 5 years have passed since last update.

virtualenv + flask + apache + wsgi で動かすまで

Posted at

virtualenv + flask + apache + wsgi で動かすまで

apacheflaskアプリケーション動かすまでのフローを駆け足で。

Werkzeug ならけっこう簡単に起動までできるけど、
apache + mod_wsgi になると途端にハードル上がるので、ざっくりまとめてみた。

全てmacの場合なので、適宜パス等は読み替えてください。

初期設定

この辺を参考に virtualenv 入れる。
http://qiita.com/k2tanaka/items/5f111612ec1b6d7584a6

mkvirtualenv -p ~/.pythonz/pythons/CPython-2.7.6/bin/python2.7  v2.7.6

workon して pipflask まで入れる。

workon v2.7.6
pip install flask

アプリケーション部分

中身はすごい適当。
とりあえず最小限の例示で。

構成

ファイルパスとかはこの後のapacheのconfに合わせるように。

/Users/kuryu/workspace/test/flask
├── app.wsgi
├── app_templates
│   └── index.html
└── main.py

中身

app.wsgi
# -*- coding:utf-8 -*-

import sys, os

import logging
# apacheのログに出すために必要
logging.basicConfig(stream = sys.stderr)

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

from main import app as application
main.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
from flask import Flask, render_template
from jinja2 import FileSystemLoader

app = Flask(__name__)
# jinja2のtemplateディレクトリ変更してみる
# 別になくてもいい。
# 省略した場合はこのファイルと同じ階層の "templates" になる。
app.jinja_loader = FileSystemLoader(
        os.path.join(os.path.abspath(os.path.dirname(__file__)), 'app_templates')
    )

@app.route("/")
def index():
    from flask import render_template
    return render_template('index.html')

@app.route("/foo")
def foo():
    return "foo"

@app.route("/foo/bar")
def foo_bar():
    return "foobar"

if __name__ == "__main__":
    app.run()
app_templates/index.html
hogehoge

apacheの設定

mod_wsgi の入れ方

は省略。
多分linuxならaptyumで入るか、最初からapacheに同梱されてる。

macなら

brew tap homebrew/apache
brew install mod_wsgi

して

brew info mod_wsgi

すればパスとかわかると思う。

confの設定

vitualenv 使うので、WSGIPythonHomepython の場所を指定する。

flask.conf
## mod_wsgi
LoadModule wsgi_module /usr/local/Cellar/mod_wsgi/3.5/libexec/mod_wsgi.so

WSGIPythonHome /Users/kuryu/.virtualenvs/v2.7.6
WSGIDaemonProcess test user=kuryu group=staff threads=5
WSGIScriptAlias /test /Users/kuryu/workspace/test/flask/app.wsgi
WSGISocketPrefix /var/run/wsgi

<Directory /Users/kuryu/workspace/test/flask>
    Options +ExecCGI
    SetHandler wsgi-script
    AddHandler wsgi-script .wsgi
    Order deny,allow
    Allow from all
</Directory>

apache再起動しておく。

sudo apachectl restart

叩いてみる

WSGIScriptAlias/test って指定してるので、urlはこう。

curl localhost/test/
curl localhost/test/foo
curl localhost/test/foo/bar

以上。

めんどくささの原因の9割はapacheなんだよな…

43
38
0

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
43
38