uwsgi + nginx 部署python Flask项目
参考:
https://www.runoob.com/django/django-nginx-uwsgi.html
https://www.jianshu.com/p/6452596c4edb
1.基本流程
# 安装flask
$ pip install flask
然后写一个简单的服务,我就写一个控制直播推流的开关
from flask import Flask
app = Flask(__name__)
global status
@app.route('/on')
def turn_on():
global status
status = 1
return 'living server is on!'
@app.route('/off')
def turn_off():
global status
status = 0
return 'living server is off!'
@app.route('/status')
def live_status():
global status
return str(status);
if __name__ == '__main__':
global status
status = 1 ;
app.run()
写好之后可以在本地跑起来试试,端口默认5000
然后安装uwsgi
$ pip install uwsgi
在/usr/local路径下建立目录写配置文件uwgsi.ini
(我们新建文件夹uwsgi_script用来放uwsgi信息)
socket = 127.0.0.1:7100
chdir = /usr/local/live
wsgi-file = server.py
callable = app
processes = 4
vacuum = true
master = true
再写nginx配置
server {
listen 8080;
server_name data.migelab.com;
charset utf-8;
client_max_body_size 75M;
location / {
include uwsgi_params; # 导入uwsgi配置
uwsgi_pass 127.0.0.1:7100; # 转发端口,需要和uwsgi配置当中的监听端口一致
uwsgi_param UWSGI_PYTHON /usr/bin/python3;
uwsgi_param UWSGI_CHDIR /usr/local/live; # 项目根目录
uwsgi_param UWSGI_SCRIPT server:app;
}
}
# 启动nginx
./nginx
# 启动uwsgi
uwsgi --ini /usr/local/live/uwsgi_script/uwsgi.ini &
2.功能升级
主要是升级两个内容:加入使用POST和GET方法;
? 返回 JSON对象的响应;
? 管理一个视频流升级为管理多个视频流
JSON格式响应:
参考链接:https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.response_class
? https://blog.csdn.net/weixin_41665106/article/details/105599235
使用JSON格式去响应前端的请求:
@app.route('/on', methods=['POST','GET'])
def turn_on():
global status
if request.method =='POST':
camera = request.form['camera']
print(camera)
if camera != KeyError:
status[int(camera)] = 1
response = make_response({
'status':'success',
'code':'200',
'ERROR':''
},200)
response.headers={
'content-type':'JSON'
}
return response
else :
response = make_response({
'status': 'fail',
'code': '400',
'ERROR':'camera code error!'
},400)
response.headers = {
'content-type': 'JSON'
}
return response
else:
response = make_response({
'status': 'fail',
'code': '500',
'ERROR': 'GET method error!'
}, 500)
response.headers = {
'content-type': 'JSON'
}
return response
处理异常:
global InvalidUsage
class InvalidUsage(Exception):
status_code = 400
def __init__(self,message,status_code=400):
Exception.__init__(self)
self.message = message
self.status_code = status_code
@app.errorhandler(InvalidUsage)
def invalid_usage(error):
response = make_response(error.message)
response.status_code = error.status_code
return response
使用了抛出异常之后,之前的响应代码就简化了许多:
@app.route('/on', methods=['POST','GET'])
def turn_on():
global status
if request.method =='POST':
camera = request.form['camera']
print(camera)
if camera != KeyError:
status[int(camera)] = 1
response = make_response({
'status':'success',
'code':'200',
'ERROR':''
},200)
response.headers={
'content-type':'JSON'
}
return response
else :
raise InvalidUsage('camera code is inValid or empty', status_code=400)
else:
raise InvalidUsage('GET method is InValid',status_code = 403)
|