[Fixed]-Python requests return file-like object for streaming

29👍

There’s an attribute Response.raw, which is already a file-like object.

resp = requests.get(url, stream=True)
resp.raw # is what you need

Using io.BytesIO(resp.content) is not preferable since behind the scenes you’re reading the same amount of data twice (also memory-wise): accessing resp.content reads everything from the network stream, then io.BytesIO(resp.content) is allocating again the same amount of memory, and then you read it from BytesIO object.

10👍

Look into the io module for using file-like objects.

Probably you could use io.BytesIO which you can initialize with the Response.content. Then instead of list of bytes you get a file-like object.

import io
resp = requests.get(url, stream=True)
obj.mp3 = io.BytesIO(resp.content)
👤dnll

1👍

Django’s responsibility is to generate the HTML code that is then interpreted by the browser. The browser is what needs to be streaming the audio. You need to pass the mp3 url through Django templates that a player like http://www.jwplayer.com/ can then stream on the client side.

Leave a comment