Skip to main content
 首页 » 编程设计

python之如何使用 Django 将图像流式传输到浏览器

2024年10月24日38kenshinobiy

如果我不正确地使用这些术语,请原谅我,我对流式传输的概念还很陌生,而且我在谷歌搜索中没有找到很多资源来讨论流式传输的最佳用例。

我现在拥有的:

浏览器向 Django 端点发出图像请求

var img = new Image(); 
img.src = 'http://www.example.com/api/images/51234/ 
img.onload = function() { 
    $('#my-img').attr('src', this.src); 
} 

Django 转身向服务发出另一个图像请求

import requests 
 
def get_image(request, img_id): 
    response = requests.get("http://api.myexample.net/album/123/img/{0}".format(img_id)) 
 
    return HttpResponse(res.content, mimetype="image/jpeg") 

我对这个过程的理解是,Django 会将此图像的所有二进制信息读入内存,然后转身将响应传递给浏览器。有没有一种方法可以直接将它流式传输到浏览器,而不是等待图像完全传送到 Python?

我已阅读 StreamingHTTPResponse 的文档类,但所有示例都只是简单地从服务器磁盘读取文件并将其传递给 StreamingHTTPResponse,而不是从其他服务获取文件。

请您参考如下方法:

这里有一种方法可以做到这一点

import requests 
# have this function in file where you keep your util functions  
def url2yield(url, chunksize=1024): 
   s = requests.Session() 
   # Note: here i enabled the streaming 
   response = s.get(url, stream=True) 
 
   chunk = True 
   while chunk : 
      chunk = response.raw.read(chunksize) 
 
      if not chunk: 
         break 
 
      yield chunk 
 
 
# Then creation your view using StreamingHttpResponse 
def get_image(request, img_id): 
   img_url = "http://api.myexample.net/album/123/img/{0}".format(img_id) 
   return StreamingHttpResponse(url2yield(img_url), content_type="image/jpeg") 

希望对您有所帮助。