python请求返回类似文件的对象以进行流式传输 [英] python requests return file-like object for streaming
问题描述
我创建了一个这样的请求对象:
obj.mp3 = requests.get('http://foo.com/bar.mp3', stream=True)
我认为我可以将这个 obj.mp3
对象提供给任何需要文件或 URI 的音频播放器,显然这个想法是错误的:没有播放.完整代码如下:
#views.py类 ArticleDetailView(DetailView):模型 = 文章template_name = 'song.html'def get_object(self):obj = super(ArticleDetailView, self).get_object()#code 将 mp3 url 存储在 obj.mp3 和其他东西中如果 obj.mp3:obj.mp3 = requests.get(obj.mp3, stream=True).content返回对象#song.html<div class="音频"><audio src={{ article.mp3 }} type="audio/mpeg">
将 requests
的返回视为我可以与播放器一起流式传输的内容的正确方法是什么?我知道至少我可以将 obj.mp3
写入文件,然后将播放器指向文件位置,但我试图避免将文件写入磁盘.
谢谢,
有一个属性 Response.raw,它已经是一个类似文件的对象.
resp = requests.get(url, stream=True)resp.raw # 就是你所需要的
使用 io.BytesIO(resp.content)
不是可取的,因为在幕后你读取相同数量的数据两次(也是内存方面):访问 resp.content
从网络流中读取所有内容,然后 io.BytesIO(resp.content)
再次分配相同数量的内存,然后您从 BytesIO 对象中读取它.
I have created a requests object like this:
obj.mp3 = requests.get('http://foo.com/bar.mp3', stream=True)
I thought that I could just feed this obj.mp3
object into any audio player that expects a file or an URI, obviously this idea is wrong: nothing played. Below are the full code:
#views.py
class ArticleDetailView(DetailView):
model = Article
template_name = 'song.html'
def get_object(self):
obj = super(ArticleDetailView, self).get_object()
#code to store mp3 url in obj.mp3 and other stuff
if obj.mp3:
obj.mp3 = requests.get(obj.mp3, stream=True).content
return obj
#song.html
<div class="audio">
<audio src={{ article.mp3 }} type="audio/mpeg">
</div>
What is the correct way of treating return from requests
as something that I can stream with a player? I know at least I can write the obj.mp3
to a file, then just point the player to the file location, but I am trying to avoid write the file to disk.
Thanks,
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.
这篇关于python请求返回类似文件的对象以进行流式传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!