我有一个 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
最佳答案
也许您没有考虑到BytesIO
是一个seekable
流并且支持当前字节位置。因此,写入后,您需要先执行 stream.seek(0)
,然后再从头开始读取或传递给 StreamingResponse
。
关于python - 当从 FastAPI 发送时流主体为满,当由请求接收时流主体为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65376633/