在apache上部署flask框架程序

flask是python的一个web开发框架,相比django来说,flask显得更加轻量级,也没有ORM实现,上手很快。总之,用flask限制很小,你可以自由发挥其它组件,比如数据库,django原生不支持mongodb的。

安装flask:

sudo apt-get install python-flask
sudo apt-get install python-virtualenv

建立一个hello world项目:

cd ~/www/
mkdir flaskdemo
cd flaskdemo
virtualenv venv
pip install Flask
vim hello.py

hello.py内容:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello world'

@app.route('/user/<username>')
def show_user_profile(username):
    return 'User %s ' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post id %d' % post_id

apache下安装mod_wsgi模块:

apt-get install libapache2-mod-wsgi

配置apache,在配置文件中加入下面配置:

    WSGIDaemonProcess flaskdemo user=chenming group=sudo threads=5
    WSGIScriptAlias /flaskdemo /home/chenming/www/flaskdemo/hello.wsgi

    <Directory /home/chenming/www/flaskdemo>
        WSGIProcessGroup flaskdemo
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>

其中/home/chenming/www/flaskdemo/hello.wsgi文件内容:

import sys
sys.path.append("/home/chenming/www/flaskdemo/")
from hello import app as application
#import app就是指的app = Flask(__name__),参考http://stackoverflow.com/questions/9680073/how-do-i-use-flask-routes-with-apache-and-mod-wsgi

启动apache,然后访问 http://127.0.0.1/flaskdemo/ 和 http://127.0.0.1/flaskdemo/user/xxx