How to make flask response to client asynchronously?

若如初见. 提交于 2019-12-05 16:59:00

问题


Flask is a single thread web server. But I want to make it won't block when handle some time consuming request.

For example:

from flask import Flask
import time
import sys
app = Flask(__name__)

@app.route("/")
def hello():
    print "request"
    sys.stdout.flush()
    for _ in range(10000000):
        for j in range(10000000):
            i = 1
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)

I want when every client request to server, it always output "request" on console immediately. I have try gunicorn and run with gunicorn -k gevent -w 4 a:app but it still appears synchronous.


回答1:


This snippet is a good starting point.

You also should look into Celery or RQ, they're the right thing to use for larger projects, more importantly they're not Flask-specific.

They also have Flask integration each, Flask-Celery and Flask-RQ.




回答2:


I believe you are asking about something called "streaming". For Flask this can be accomplished using generator functions and the yield keyword.

Streaming is covered in more detail in the official Flask documentation, have a look here.



来源:https://stackoverflow.com/questions/18975851/how-to-make-flask-response-to-client-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!