问题描述
我以前使用的是女服务员。现在,我使用Gevent来运行只有一个API的Flask应用
from flask import Flask,request,jsonify
import documentUtil
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
@app.route('/post-document-string',methods=['POST'])
def parse_data():
req_data = request.get_json(force=True)
text = req_data['text']
result = documentUtil.parse(text)
return jsonify(keywords = result)
if __name__=='__main__':
http_server = WSGIServer(('127.0.0.1',8000),app)
http_server.serve_forever()
这很好。但是API不是异步的。如果从前端,我同时启动两次相同的API,则第二个调用将等待第一个调用首先响应。
这是怎么了?如何使其异步?
解决方法
我们使用Gunicorn在多个进程中运行Flask。通过这种方式,您可以从python中获得更多汁+自动重新启动等功能。样本配置文件:
import multiprocessing
bind = "0.0.0.0:80"
workers = (multiprocessing.cpu_count() * 2) + 1
# ... additional config
然后以类似的方式运行
gunicorn --config /path/to/file application.app
,
不确定,但是我认为在服务器对象中添加 线程参数 可以解决问题。
http_server = WSGIServer(('127.0.0.1',8000),app,numthreads=50)
来源:https://f.gallai.re/wsgiserver
,"""index.py"""
from flask import Flask
from flask import jsonify
app = Flask(__name__)
@app.route('/')
def index():
"""Main page"""
doc = {
'site': 'stackoverflow','page_id': 6347182,'title': 'Using Gevent in flask'
}
return jsonify(doc)
# To start application
gunicorn -k gevent --bind 0.0.0.0 index:app
k : worker_class
--bind : bind address
# See https://docs.gunicorn.org/en/latest/settings.html