官方其實已經給出了方案,只不過藏的有點深,在加上網上有很多不太靠譜的帖子誤導了我(當然不排除我沒理解的原因哈)。所以為了讓有些朋友的少走點彎路,也為給自己做個備忘。
完整代碼:https://github.com/wskssau/my_notespace的 python/todo_app
解決方案: flask+gevent
安裝gevent
pip install gevent
修改代碼
# 文件頭部from gevent import monkeyfrom gevent.pywsgi import WSGIServer# 在玩websockets,可以無視之哈,有空貼下flask websockets實現哈from geventwebsocket.handler import WebSocketHandlerimport time# gevent的猴子魔法monkey.patch_all()app = Flask(__name__)app.config.update( DEBUG=True)@app.route('/asyn/1/', methods=['GET'])def test_asyn_one(): if request.method == 'GET': time.sleep(10) return 'hello asyn'@app.route('/test/', methods=['GET'])def test(): return 'hello test'if __name__ == "__main__": # app.run() http_server = WSGIServer(('', 5000), app, handler_class=WebSocketHandler) http_server.serve_forever()
運行之后可以先訪問/asyn/1/再訪問/test/,可以明顯發現,/asyn/1/在做耗時任務時不會影響其他請求
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答