本文介绍了如何使烧瓶异步响应客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask是一个单线程的Web服务器。但是,我想让它不会阻止处理一些耗时的请求。



例如:

  from flask import Flask 
import time $ b $ import sys $ b $ app app = Flask(__ name__)

@ app.route(/ )
def hello():
printrequest
sys.stdout.flush()
在范围内(10000000):
(10000000):
i = 1
返回Hello World!

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

我希望当每个客户端请求到服务器时,它总是立即在控制台上输出请求。我已经尝试使用 gunicorn 并运行 gunicorn -k gevent -w 4 a:app ,但它仍然显示同步。 / p>

解决方案

我相信你正在问一些叫做streaming的东西。对于Flask,这可以通过使用生成器函数和 yield 关键字来完成。



更详细地介绍官方的Flask文档,看看。


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.

解决方案

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.

这篇关于如何使烧瓶异步响应客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:47
查看更多