【问题标题】:Flask streaming doesn't return back response until finished烧瓶流在完成之前不会返回响应
【发布时间】:2020-04-29 05:26:33
【问题描述】:

所以我正在尝试流式传输从 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】:

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

    但 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)
    

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 2019-02-24
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2019-06-17
      • 1970-01-01
      相关资源
      最近更新 更多