问题描述
Flask是单线程Web服务器.但是我想使它在处理一些耗时的请求时不会阻塞.
Flask is a single thread web server. But I want to make it won't block when handle some time consuming request.
例如:
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)
我想要每一个客户端请求到服务器时,它总是总是立即在控制台上输出"request".我已经尝试gunicorn
并与gunicorn -k gevent -w 4 a:app
一起运行,但是它仍然显示为同步.
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.
推荐答案
我相信您正在询问所谓的流媒体"问题.对于Flask,可以使用生成器函数和yield
关键字来实现.
I believe you are asking about something called "streaming". For Flask this can be accomplished using generator functions and the yield
keyword.
Flask官方文档中详细介绍了流媒体,请在此处.
Streaming is covered in more detail in the official Flask documentation, have a look here.
这篇关于如何使烧瓶对客户端进行异步响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!