I have an api in which the server sends a stream of data to the client. On the server-side, the stream object is populated. I can verify this by writing to a file on the server before sending. But when the client receives the stream and tries to write it to memory, it always results in an empty file. Here is my code
TL;DR: Stream is not empty when sent from api, but is empty when client recieves and tries to write
Server-side - sending io.BytesIO
object
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)
Client-side - receiving io.BytesIO
object and trying to write
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
Does anyone have any ideas? I have looked at these links and more with no luck. Thank you!