2013年11月7日 星期四

[Python] Bottle + Nginx + uWSGI @ Ubuntu 12.04

環境:

$ sudo apt-get install python-bottle nginx uwsgi uwsgi-plugin-python

Python Bottle 範例 (/var/www/bottle_app):

$ vim /var/www/bottle_app/app.py
from bottle import Bottle, route, run, install, template, static_file
#from bottle_sqlite import SQLitePlugin

#import bottle
#application = bottle.default_app()

app = application = Bottle()
#app.install(SQLitePlugin(dbfile='/tmp/test.db'))

@app.route('/')
def index():
        return template('Hello world')

if __name__ == '__main__':
        run(app, host='0.0.0.0', port=1234)


設定 uWSGI:

$ sudo vim /etc/uwsgi/apps-available/bottle_app.ini
[uwsgi]
socket = /run/uwsgi/app/bottle_app/socket
chdir = /var/www/bottle_app
master = true
plugins = python
file = app.py
uid = www-data
gid = www-data
$ sudo ln -s /etc/uwsgi/apps-available/bottle_app.ini /etc/uwsgi/apps-enabled/bottle_app.ini
$ sudo service uwsgi restart


設定 nginx:

$ sudo vim /etc/nginx/sites-available/bottle_app
upstream _bottle {
server unix:/run/uwsgi/app/bottle_app/socket;
}

server {
listen 8080;
root /var/www/bottle_app;

location / {
try_files $uri @uwsgi;
}

location @uwsgi {
include uwsgi_params;
uwsgi_pass _bottle;
}
}

$ sudo ln -s /etc/nginx/sites-available/bottle_app /etc/nginx/sites-enabled/bottle_app
$ sudo service nginx restart


其他部分,對於 /var/www/bottle_app/app.py 留意 application 變數是 uwsgi 尋找的對象,若想要改變可以在 uwsgi 定義 callable (預設 callable = application)。

至於使用 bottle 開發上麻煩的地方是 templates(views) 更新後,必須重新啟動才能生效,就算改用 uwsgi 也沒有改善,不知是不是少設定甚麼,或是預設規劃就是如此?

除此之外,若不用那麼著重效率,還可以替換掉 Bottle 預設的 wsgiref WSGIServer (non-threading HTTP server),而且改法很簡單(switching-the-server-backend):

$ sudo apt-get install python-paste
$ vim app.py
...
if __name__ == '__main__':
import paste
run(
app ,
host='0.0.0.0',
port=1234,
server='paste'
)

沒有留言:

張貼留言