Reputation: 100
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
io.BytesIO
objectfrom 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
object and trying to writeimport 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!
Upvotes: 2
Views: 1666
Reputation: 32053
Perhaps you did not consider that BytesIO
is a seekable
stream and supports the current byte position. Therefore after writing to it you need to do stream.seek(0)
before reading from beginning or passing to StreamingResponse
.
Upvotes: 2