Flaskは高い同時実行性とマルチスレッドを処理します



Flask Handles High Concurrency



序文:
フラスコをサービスとして使用する場合、python run.pyを使用して実行できますが、これは本番環境では使用できず、接続が応答しない場合があります。その後、情報を検索したところ、主に次の側面で、フラスコサービスがマルチスレッドと高い同時実行性を処理していることがわかりました。

1.マルチスレッドの効果を実現するためにapp.run()のパラメーターを設定することにより、特定のパラメーターは次のようになります。



# 1.threaded: Multithreading support, the default is False, that is, multithreading is not enabled app.run(threaded=True) # 2.processes: the number of processes, the default is 1. app.run(processes=True) ps: Multi-process or multi-thread can only choose one, not at the same time

2.高い同時実行性を解決するためのコルーチンとしてgenventを使用します。

from genvent.wsgi import WSGIServer from genvent import monkey monkey.patch_all() app = Flask(__name__) app.config.from_object(config) api = Api(app) db = DBInfo() # db_old = DBInfo_old()

次に、WSGIServer((address、port)、app).serve_forever()をこのようにラップします
pythoncode.pyを使用してサービスを開始します



3.アプリをGuicorn(genvent付き)の形式でパッケージ化して、サービスを開始します
コードを使用してプロジェクトを開始します

# Start command gunicorn -c gun.py thread_explore:app

ここで、gun.pyはgunicornの構成ファイルです。
thread_exploreはサービスのメインプログラムです
アプリはフラスコのアプリです
gun.pyの特定のコンテンツ:

import os import gevent.monkey gevent.monkey.patch_all() import multiprocessing # Service address (adderes:port) bind = 127.0.0.15000 # Number of startup processes workers = multiprocessing.cpu_count() * 2 +1 worker_class = 'gevent' threads = 20 preload_app = True reload = True x_forwarded_for_header = 'X_FORWARDED-FOR'

ps:ここでの起動プロセスの数は、CPUの数、できれば2 * CPUの数+1に従って決定する必要があります。
参考資料:
https://www.jianshu.com/p/a90775e33b52
https://www.cnblogs.com/lesliexong/p/9396850.html





リンク:https://www.jianshu.com/p/79489cfc6fb9