フラスコでのGeventの使用:APIは非同期ではありません
Aug 18 2020
以前はウェイトレスを使用していました。現在、Geventを使用して、APIが1つしかない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を同時に2回起動すると、2番目の呼び出しは最初の呼び出しが最初に応答するのを待ちます。
ここで何が問題になっていますか?どうすれば非同期にすることができますか?
回答
1 AlexWeavers Sep 01 2020 at 14:30
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
1 pritesh Sep 07 2020 at 06:43
よくわかりませんが、サーバーオブジェクトにスレッドパラメータを追加することで問題を解決できると思います。
http_server = WSGIServer(('127.0.0.1', 8000), app, numthreads=50)
ソース: https://f.gallai.re/wsgiserver
1 EM28 Sep 07 2020 at 23:17
"""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