返回生成器在 WSGI 服务器上不起作用,但在本地没有问题

Returning generators not working on WSGI server but is fine locally

提问人:No Name 提问时间:10/6/2023 更新时间:10/6/2023 访问量:26

问:

这可能是一个棘手的问题,但从本质上讲,我希望服务器返回(产生)一个文本,等待片刻,然后在同一连接上返回另一个文本。下面是一个示例服务器代码:

from flask import Flask,request
from time import sleep

app = Flask(__name__)

def generator():
    for _ in range(5):
        yield "test" #https://stackoverflow.com/questions/18567773/return-multiple-values-over-time
        sleep(0.5)

@app.route('/',methods=["GET","POST"])
def index():

    return generator() #https://stackoverflow.com/questions/55736527/how-can-i-yield-a-template-over-another-in-flask

我已经在 localhost 上测试了此代码的类似版本,并且运行良好。我使用 curl 连接到 localhost,它打印了 test、wait 和 printed test 等。

但是,当尝试将其托管在 pythonanywhere 上时,它引发了:

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a generator. 

我知道我可以将它包装在 Response() 中,但这会擦除时间延迟元素。我不确定该怎么做。

python 烧瓶 生成器 WSGI

评论

0赞 Glenn 10/6/2023
我们这里有一些关于这方面的文档:help.pythonanywhere.com/pages/Buffering
0赞 No Name 10/7/2023
哇,谢谢@Glenn。添加 response.headers['X-Accel-Buffering'] = 'no' 解决了这个问题。

答: 暂无答案