Apache + Flask + mod_wsgi + Koding 部署小记

转自:http://www.isaced.com/post-238.html

之前发现了Koding,一直没怎么注意,今天试用了一下练练手,也算是第一次在真正的服务器上操作,用它搭个Flask站点出来,一路也是坑坑包包啊,特别是Apache的配置,复杂的无脑,第一次搞还是推荐先看看Apache的文档。话说Koding还真是不错,虽然不能拿来当生产环境,弄弄玩还是挺好,特别是像我们这种新手来练手。用Koding的原话来说是这样:

Koding is first and foremost a Development Environment, and not a Production Host.
VMs Shutdown After Logout,Approximately 20 minutes after you log out, your Free VMs will shut down.

如上所说,Koding是一个开发环境而不是生产环境,这也是Koding主办方的意思。在退出登陆后20分钟,你的主机将会自动关闭,详情可见Koding的FAQ页面。
不过这已经很好了,完全和真实主机一模一样,支持SSH远程登陆,强大的Web面板(支持文件浏览和Terminal),用来学习已经完全足够了。

安装 mod_wsgi
如果服务器是用的Apache,那么Flask官方推荐用mod_wsgi,文档可以戳这,其实Flask官方文档已经写的很清楚了,我还是贴一下吧。

Ubuntu or Debian:

apt-get install libapache2-mod-wsgi

修改Apache配置:
然后修改/etc/apache2/sites-enabled/000-default:

WSGIPythonPath /home/isaced/test                                                                                                                                                   

    ServerAdmin webmaster@localhost
    DocumentRoot /home/isaced/test/
    WSGIScriptAlias / /home/isaced/test/app.wsgi                                                                                                                                       
                                                                                                                                                     
                                                                                                                                                                   
    Order deny,allow
    Allow from all


    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined

添加.wsig文件
然后在isaced目录下新建项目目录”test“,其中新建文件app.wsgi,内容如下:

def application(environ,start_response):
    status='200 OK'
    output='Hello wsgi!'
    response_headers=[('Content-type','text/plain'),
                       ('Content-Length',str(len(output)))]
    start_response(status,response_headers)
    return[output]

赶紧试试
重启Apache试试,看看效果吧:

sudo /etc/init.d/apache2 restart

浏览器打开“http://xxx.kd.io/”,就会输出“Hello wsgi!”。

启动Flask
按耐住小鸡动,我们继续来启动一个flask实例。

新建test.py文件,作为flask入口文件,内容如下:

from flask import Flask
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return "Hello World!"
 
if __name__ == '__main__':
    app.run(host='0.0.0.0')

然后修改app.wsgi文件内容为:

from test import app as application
这里的test就是当前目录的test.py文件,看到网上很多文章还要import sys,再append当前目录,其实如果在同一目录下的话就不需要了。

你可能感兴趣的:(Apache + Flask + mod_wsgi + Koding 部署小记)