将文件从远程URL流到Django视图响应 [英] Stream file from remote url to Django view response
问题描述
是否可以使用Django Response从远程URL流式传输文件(无需在本地下载文件)?
Is there any way to stream file from remote URL with Django Response (without downloading the file locally)?
# view.py
def file_recover(request, *args, **kwargs):
file_url = "http://remote-file-storage.com/file/111"
return StreamFileFromURLResponse(file_url)
我们有文件存储空间(文件可以很大-1 GB或更多)。我们无法共享下载网址(存在安全问题)。通过将下载流转发到Django响应,文件流传输可以显着提高
的下载速度。
We have file storage (files can be large - 1 GB and more). We can't share download url (there are security issues). File streaming can significantly increase download speed by forwarding download stream to Django response.
推荐答案
Django内置了 StreamingHttpResponse 类,应为其提供迭代器,该迭代器产生字符串作为内容。在下面的示例中,我正在使用 requests
原始响应内容
Django has built in StreamingHttpResponse class which should be given an iterator that yields strings as content. In example below I'm using requests
Raw Response Content
import requests
from django.http import StreamingHttpResponse
def strem_file(request, *args, **kwargs):
r = requests.get("http://host.com/file.txt", stream=True)
resp = StreamingHttpResponse(streaming_content=r.raw)
# In case you want to force file download in a browser
# resp['Content-Disposition'] = 'attachment; filename="saving-file-name.txt"'
return resp
这篇关于将文件从远程URL流到Django视图响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!