Stream file from remote url to Django view respons

2020-02-29 19:56发布

问题:

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)

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.

回答1:

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