Open
Description
环境与依赖
- python版本 : 2.7.X
- flask : web框架
- gunicorn : python 的 web服务网关(Python Web Server Gateway Interface,缩写为WSGI)
- Supervisor : 守护进程,用于守护 gunicorn 服务
具体的安装方法如下:
# 安装opencv库
[root@localhost ~]# pip install opencv-python
# 安装flask web框架
[root@localhost ~]# pip install flask
# 安装gunicorn
[root@ localhost ~]# pip install gunicorn
Web服务配置
步骤1: 使用flask编写Web服务,test.py
# -*- coding: UTF-8 -*-
from flask import Flask, abort, request, jsonify, json
import time
app = Flask(__name__)
"""
报文响应DTO
"""
class Response():
code = "9999"
msg = ""
# 转换成JSON
def toJSON(self):
dict = {}
dict["code"] = self.code
dict["msg"] = self.msg
return jsonify(dict)
#-------------------------------------------
# 外部接口
#-------------------------------------------
"""
功能: 测试入口
"""
@app.route('/test', methods=['POST'])
def test():
response = Response()
response.code = "0000"
response.msg = "成功"
print "****请求处理结束****"
return response.toJSON()
"""
主函数
"""
def main():
app.run(debug=False)
# app.run(host="0.0.0.0", port=8383, debug=False)
#Exec Entry
if __name__ == '__main__':
try:
main()
except Exception,e:
print "exception:{}".format(e)
print " :( bye!"
步骤2:设置gunicorn服务(Supervisor守护进程方式启动)
由于flask程序是单进程程序,只能同时处理一个并发,可以采用 gunicorn 服务解决该问题,下面是具体的安装步骤:
1、 安装Supervisor守护进程
按照下面文章的方法,安装Supervisor守护进程,安装完成后启动Supervisor守护进程
2、Supervisor守护进程设置gunicorn
[root@localhost ~]# vi /etc/supervisor/test.conf
[program:test]
directory=/home/test
user=root
command=gunicorn -w 2 -b 0.0.0.0:9982 test:app -t 500 --access-logfile /home/test/log/gunicorn_access.log
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/home/test/log/supervisor.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=7
stdout_capture_maxbytes=50MB
stdout_events_enabled=false
[group:testgroup]
programs=test
priority=999
备注:
gunicorn -w 5
指的是开启5个工作进程, 并且gunicorn
可以充当工作进程的守护进程;- 可以通过查看当前CPU核心数,来判断需要开启几个工作进程:
cat /proc/cpuinfo| grep "processor"| wc -l
gunicorn -w 2 -b 0.0.0.0:9982 test:app
, 这里的test
是web服务的pyhton文件名(test.py)
步骤3: 配置Nginx
[root@localhost ~]# vi /etc/nginx/conf.d/test.conf
upstream flaskupstream {
# server-A
server 127.0.0.1:9982;
# server-B
server 127.0.0.1:9983;
}
server {
listen 9981;
server_name _;
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 300;
proxy_pass http://flaskupstream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/access_error.log;
}
error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# root html;
# }
}
[root@localhost ~]# nginx -s reload
安装过程记录
问题1:libSM.so.6: cannot open shared object file: No such file or directory
解决方法:
[root@localhost ~]# sudo yum install libXext libSM libXrender