如何让烧瓶流逐行输出?

How to make flask stream output line by line?

我有一个生成 CSV 的生成器函数,并且根据 Flask's documentation 我将该函数传递到 Response 对象中。

app.route("/stream")
...
def generate():

        yield ",".join(result.keys()) #Header

        for row in result:
            yield ",".join(["" if v is None else str(v) for v in row])

return current_app.response_class(stream_with_context(generate()))

当我去阅读 Request 中的响应时,我得到的响应是一个巨大的字符串,而不是逐行获取,因此它可以写入 csvwriter

s = requests.Session()

with s.get(
    urllib.parse.urljoin(str(current_app.config["API_HOST_NAME"]), str("/stream")),
    headers=None,
    stream=True,
) as resp:
    for line in resp.iter_lines():
        if line:
            print(line) #All the rows are concatenated in one big giant String
            cw.writerow(str(line, "utf-8").split(","))

如您在发布的文档中所见:

yield f"{','.join(row)}\n"  # <=== Newline at the end!

yield 语句中提供了新行。如果你不换行,你将不会在响应中得到一个。只需添加 + '\n'.