当从 FastAPI 发送时流主体是完整的,当被请求接收时是空的

stream body full when sent from FastAPI, empty when received by requests

我有一个 api,其中服务器向客户端发送数据流。在服务器端,流对象被填充。我可以通过在发送前写入服务器上的文件来验证这一点。但是当客户端接收到流并尝试将其写入内存时,它总是会导致一个空文件。这是我的代码

TL;DR:从 api 发送时流不为空,但在客户端接收并尝试写入时为空

服务器端 - 发送 io.BytesIO 对象

from io import BytesIO
from fastapi import FastAPI
app = FastAPI()

# capture image and store in io.BytesIO stream
def pic_to_stream(self):
        io = BytesIO()
        self.c.capture(io, 'jpeg')  # populate stream with image
        return io

# api endpoint to send stream
@app.get('/dropcam/stream')
def dc_stream():
    stream, ext = cam.pic_to_stream()
    # with open('example.ext', 'wb') as f:
    #     f.write(stream.getbuffer())  # this results in non-empty file on server
    return StreamingResponse(stream, media_type=ext)

客户端 - 接收 io.BytesIO 对象并尝试写入

import requests

def recieve_stream():
    url = 'http://abc.x.y.z/dropcam/stream'
    local_filename = 'client/foo_stream.jpeg'
    with requests.get(url, stream=True) as r:
        with open(local_filename, 'wb') as f:
            f.write(r.content) # this results in an empty file on client

有人有什么想法吗?我看过 these and more 没有运气。谢谢!

可能你没有考虑到BytesIO是一个seekable流,支持当前字节位置。因此,在写入它之后,您需要先执行 stream.seek(0) ,然后再从头开始阅读或传递给 StreamingResponse.