烧瓶流式传输直到完成后才返回响应

问题描述 投票:1回答:1

因此,我试图流式处理从sql数据库返回的数据块。这些块似乎正在流式传输,但是当我命中端点时,它在请求完成时在最后显示响应,而不是逐块显示流式数据。我知道已经对此有疑问,但添加mimetype似乎对我不起作用。我有以下代码:

非常感谢您的帮助!

       def generate_chunks():
            result = _get_query_service(repo_url, True).stream_query(qry)
            chunk_counter = 0

            while True:
                chunk = result.fetchmany(5)
                chunk_counter += 1
                if not chunk:
                    break
                for value in chunk:
                    yield str(chunk)

        return Response(stream_with_context(generate_chunks()), content_type='application/json', status=200)
python python-3.x flask generator flask-sqlalchemy
1个回答
0
投票

实际上这是一件小事。上面的代码有效。

但是诸如Postman和Insomnia之类的工具不支持流数据。

[如果您想查看实际运行中的数据,请使用CURL或python请求。

对于CURL,您需要添加--no-buffer选项以查看流数据。

curl --no-buffer -v http://localhost:8082/healthy

对于Python请求,您需要添加stream=True。示例:

r = requests.post('http://localhost:8082/stream_query', json=dc, stream=True)

r.encoding = 'utf-8'

for line in r.iter_content(chunk_size=10): # prints the streamed data in chunks
    print(line)
© www.soinside.com 2019 - 2024. All rights reserved.