flask + nginx + uwsgi

套件簡略說明

flask: python micro web framework
nginx: web socket service
uwsgi: protocol between python and nginx
--------------------------------------------------
環境介紹

os: ubuntu 64bit
web server: nginx + uwsgi + uwsgi-plugin-python
web framework: python 2.7 + flask

other packages: pip, virtualenv
--------------------------------------------------
套件安裝

1. virtualenv: sudo apt-get install virtualenv
2. nginx: sudo apt-get install nginx uwsgi  uwsgi-plugin-python
3. flask: pip install flask (在虛擬環境下)

ps. 系統不要裝 pip,以免虛擬環境安裝套件時安裝到系統上
--------------------------------------------------
環境建置

1. virtualenv

root> virtualenv /var/www/app/venv
root> source /var/www/app/venv/bin/activate  #進入虛擬環境
(venv) root> #前綴字表示虛擬環境

2. environment configure
  (1) nginx

#nginx configuration: /etc/nginx/sites-enables/flask.conf

root> rm /etc/nginx/sites-enables/default
root> cat /etc/nginx/sites-enables/flask.conf
server {
    listen      80;
    server_name localhost;
    charset     utf-8;
    client_max_body_size 75M;

  
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/app/uwsgi.sock;
    }

    location /static {
    root /var/www/app/;
    }
}

root> service nginx restart

  (2) uwsgi

#uwsgi configuration: /var/www/app/uwsgi.ini

root> cat /var/www/app/uwsgi.ini

[uwsgi]
#application's base folder
base = /var/www/app
#python module to import
module = hello
#the variable that holds a flask application inside the module imported at line #6
callable = app
#socket file's location
socket = /var/www/app/uwsgi.sock
#permissions for the socket file
chmod-socket    = 666
#Log directory
logto = /var/log/uwsgi/app/app.log

chdir = /var/www/app

3. Hello World!!!

(venv) root> vim /var/www/app/hello.py #對應到 uwsgi.ini module name

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

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

(venv) root> uwsgi --ini uwsgi.ini  --plugin python &

4. create system service uwsgi and load uwsgi.ini

作法一:
建立 /etc/init/uwsgi.conf
內容
description "uWSGI instance to serve myapp"

start on runlevel [2345]
stop on runlevel [!2345]

script
    cd /var/www/app
    source venv/bin/activate
    exec /usr/local/bin/uwsgi --ini uwsgi.ini --plugin python
end script

這作法我沒有成功,所以各位自己試試,後來查到另一種作法,請參考作法二

作法二:
建立 /lib/systemd/system/uwsgi.service
內容
[Unit]
Description=uWSGI Emperor
After=syslog.target

[Service]
ExecStart=/usr/local/bin/uwsgi --ini /var/www/app/uwsgi.ini --plugin python
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target

執行
sudo systemctl enable uwsgi.service
sudo systemctl start uwsgi
--------------------------------------------------

reference: uWSGI
Set up Nginx and uWSG 
How to Set Up Django with Nginx, uWSGI & systemd on Debian/Ubuntu

留言

這個網誌中的熱門文章

[IIS] 自我簽署憑證來啟用SSL

相見恨晚的自動化測試開發工具 Sikuli

sqlplus 中文亂碼解決方案