配置uwsgi.ini文件,使用systemd管理

2020-05-20  本文已影响0人  Odven

访问流程图

1. client ---> uwsgi ---> flask后台程序
2. client ---> nginx ---> uwsgi --> flask后台程序  (生产上一般都用这个流程)

为什么要用uwsgi

1. Flask: 轻量级web frame,用于路由和业务逻辑处理,有自带的简单webserver,但是是单进程,只适用于开发模式,无法支撑生产环境
2. uwsgi提高并发访问支持(-p 进程数, --threads  线程数),提高服务运行稳定性等

下面的访问流程是 client ---> uwsgi ---> flask后台程序

1) uwsgi.ini配置文件

[uwsgi]
uid=1003
gid=1003  
# 可直接提供服务让网页访问
http=0.0.0.0:3031  
# 如果web服务不支持uwsgi时用
# http-socket=127.0.0.1:3031   
# socket模式
# socket=127.0.0.1:3031 
# 却换到项目录
chdir=/mnt/flask_project/
# flask后台程序
wsgi-file=flask_test.py
# flask后台程序里面的app=Flask(__name__)实例化出来的app
callable=app
processes=1
threads=5
master=true
stats=127.0.0.1:9191
procname-master=flask-master
procname=flask
thunder-lock=true
log-format=[%(ltime)] %(addr) %(user) %(method) %(uri) %(status) %(proto) %(size) %(msecs)ms %(referer) %(uagent)
# 这个是直接 uwsgi --ini uwsgi.ini 后台运行时用的 (要注释下一行)
# daemonize=/mnt/flask_project/log.log 
# 如果用systemd管理时用的  (要注释上一行)
logto=/mnt/flask_project/log.log  
pidfile=/mnt/flask_project/uwsgi-flask.pid
vacuum=true

2) systemd管理配置文件

[Unit]
Description=flask uwsgi server daemon

[Service]
Type=notify
ExecStart=/usr/local/bin/uwsgi --ini /mnt/flask_project/uwsgi.ini
ExecReload=/bin/kill -HUP $MAINPID
KillSignal=SIGQUIT
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

3) flask_test.py

#!/usr/bin/env python3
# _*_ coding:utf-8 _*_

import json
import pymongo
from flask_cors import CORS
from flask import Flask, request, jsonify
from PIL import Image
from pyzbar.pyzbar import decode

conn = pymongo.MongoClient("mongodb://root:123@127.0.0.1:27017/admin", connect=False)
db = conn["test"]

app = Flask(__name__)
CORS(app, supports_credentials=True)
# CORS(app, resources=r'/*')

@app.route("/api/identifyQrCodes", methods=["POST"])
def IdentifyQrCodes():
    img_file = request.files.get("file")
    if not img_file:
        print("没有二维码图片文件")
        return jsonify({"data": "没有二维码图片文件"})

    try:
        img = Image.open(img_file)  # 打开二维码图片
        barcodes = decode(img)  # 解析二维码
    except Exception as e:
        return jsonify({"data": "文件格式不正确"})

    url_list = list()
    for barcode in barcodes:
        url = barcode.data.decode("utf-8")
        url_list.append(url)

    print(url_list)
    return jsonify({"data": url_list})


if __name__ == '__main__':
    app.run()
上一篇 下一篇

猜你喜欢

热点阅读