python - 当从 FastAPI 发送时流主体为满,当由请求接收时流主体为空

标签 python python-3.x python-requests fastapi bytesio

我有一个 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 linksmore没有运气。谢谢!

最佳答案

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

关于python - 当从 FastAPI 发送时流主体为满,当由请求接收时流主体为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65376633/

相关文章:

Python:如何在数字初级排序中执行二级降序字母排序

python - 计算字典中 get 方法返回第二个选项的次数

python-3.x - 为什么我在Python中得到重复的输出?

python - 可靠高效的 Linux 键值数据库?

ascii的Python产物,错误的启动

python-3.x - 使用 Pandas 数据框识别重复组

django - 如何将 Django uploadedfile.InMemory 转换为 numpy 数组或图像

python - 使用 Python 请求测量网站加载时间

python - 我如何找到为什么 python 脚本在不同机器上的运行时间明显不同?

python - 如何使用 tf.train.Checkpoint 在 tensorflow 2.0 中保存和加载选定变量和所有变量?