Python-Flask 使用

Flask 使用。

安装

1
sudo pip install flask

结合 gunicorn 和 supervisor

安装:

1
2
sudo pip install gunicorn
sudo pip install supervisor

在 supervisor 中启动 gunicorn:

项目目录下创建配置文件:

1
echo_supervisord_conf > supervisord.conf

添加:

1
2
3
[program:faceServer]
directory = /Users/apple/Desktop/CTO/JianYiKeJi/FaceServer
command = gunicorn -w 2 -b 0.0.0.0:18888 face_server:app

添加到启动项中:

1
2
vi /etc/rc.d/rc.local
supervisord -c /Users/apple/Desktop/CTO/JianYiKeJi/FaceServer/supervisord.conf

停止 Supervisor 的命令:

1
supervisorctl stop all

报错解决

异常:

1
Error: Another program is already listening on a port that one of our HTTP servers is configured to use.  Shut this program down first before starting supervisord.

解决:

1
sudo unlink /var/run/supervisor.sock 或 sudo unlink /tmp/supervisor.sock

监听连接断开

由于 FLASK 的 ErrorHandler 并不能处理,Socket 断开的事件,所以要自己处理。

1
2
3
4
5
6
7
def startVideoTransfer():
global clients
try:
app.run(host = '127.0.0.1', port = 5000, debug = False, passthrough_errors = True)
except Exception, ex:
clients -= 1
startVideoTransfer()

每次断开的话,其内部会断开服务,所以要重启服务。