最近用python寫了個小服務,既然都用python寫了,不如順便用python的服務器來運行,簡單搜索後決定用Flask+uwsgi+nginx來實現。virtualenv的安裝就不多說了。
#新建一個python3虛擬環境emailApp
mkdir pythons
cd pythons
virtualenv --python=/usr/local/bin/python3.5 emailApp
source emailApp/bin/activate
#安裝uwsgi和Flask
pip install uwsgi Flask
cd emailApp
#新建emailApp1.py
#!/root/42/pythons/emailApp/bin/python
# -*- coding: utf8 -*-
from flask import Flask,request
import json
app = Flask(__name__)
def getTS():
TS={}
nowTS=int(time.time())
TS['当前时间戳']=str(nowTS)
localTimeString=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(nowTS)))
TS['服務器時間']=str(localTimeString)
gmtTimeString=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(int(nowTS)))
TS['GMT時間']=str(gmtTimeString)
localTSToday=int(time.mktime(time.strptime(localTimeString[:10], '%Y-%m-%d')))
TS['服務器今天時間戳']=str(localTSToday)
print('服務器今天時間戳'+str(localTSToday))
TS['GMT今天時間戳']=str(localTSToday+time.timezone)
return TS
@app.route('/')
def hello_world():
return 'Good luck!'
@app.route('/taskCms/service/getTS')
def checkTS():
TS = getTS()
return json.dump(TS)
if __name__ == '__main__':
# app.debug = True
# app.run(host='0.0.0.0',port=8080)
app.run()
#此時執行
python emailApp1.py
#即可在本地http://127.0.0.1:5000/訪問到服務了。
#Ctrl+C關閉測試,新建nginx站點配置文件emailApp.conf
#nginx站點配置通常在/etc/nginx/conf.d
server {
listen 8042;
server_name 127.0.0.1;
charset utf-8;
location / { try_files $uri @yourapplication; }
location @yourapplication {
include uwsgi_params;
uwsgi_pass 127.0.0.1:3031;
}
}
#測試nginx配置文件是否有誤
nginx -t
#重新加載nginx
nginx -s reload
#此時訪問你的ip加端口號8042,出現502 Bad Gateway則證明nginx已配置好
#若出現訪問超時則可能是有防火牆阻擋
#接下來在項目目錄下新建config.ini作為uwsgi的配置文件
[uwsgi]
socket = 127.0.0.1:3031
chdir = /root/42/pythons/emailApp
master = true
binary-path = /root/42/pythons/emailApp/bin/uwsgi
virtualenv = /root/42/pythons/emailApp
module = emailApp1:app
processes = 2
threads = 4
#使用uwsgi運行Flask程序
/root/42/pythons/emailApp/bin/uwsgi --ini /root/42/pythons/emailApp/config.ini
#如果遇到uwsgi: error while loading shared libraries: libpcre.so.1可嘗試
ln -s /usr/local/lib/libpcre.so.1 /lib64
#正常的話此時應該能通過8042訪問到服務
#開機啟動我使用的centos6自帶的Upstart
nano /etc/init/uwsgi.conf
# simple uWSGI script
description "uwsgi tiny instance"
start on runlevel [2345]
stop on runlevel [06]
respawn
exec /root/42/pythons/emailApp/bin/uwsgi --ini /root/42/pythons/emailApp/config.ini
最後可以通過screen執行uwsgi,然後退出服務器。這樣就完成了一個簡單Flask項目的搭建。Flask就是簡單快速。
如果是通過Upstart自動啟動的,可以通過initctl reload uwsgi和initctl restart uwsgi來重啟uwsgi。
Connection reset by peer鏈接被中斷
過了幾天發現接口不穩定,有時能正常返回數據,有時出現Connection reset by peer鏈接被中斷。從firebug里看發現數據返回有時是先返回個0,就是什麼也沒有然後真是數據才回來,這是瀏覽器已經報錯了。此時可嘗試在uwsgi配置中增加buffer-size=65535和post-buffering = 1。以及在nginx的conf中設置
http{
...
keepalive_timeout 0;
uwsgi_read_timeout 86400;
uwsgi_send_timeout 86400;
....
}
本文更新於 2017/03/09。