Django Filewrapper memory error serving big files, how to stream

后端 未结 1 358
日久生厌
日久生厌 2020-12-20 09:08

I have code like this:

@login_required
def download_file(request):
    content_type = \"application/octet-stream\"
    download_name = os.path.join(DATA_ROOT         


        
相关标签:
1条回答
  • 2020-12-20 09:27

    Try to use StreamingHttpResponse instead, that will help, it is exactly what you are looking for.

    Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage?

    import os
    from django.http import StreamingHttpResponse
    from django.core.servers.basehttp import FileWrapper #django <=1.8
    from wsgiref.util import FileWrapper #django >1.8
    
    @login_required
    def download_file(request):
       file_path = os.path.join(DATA_ROOT, "video.avi")
       filename = os.path.basename(file_path)
       chunk_size = 8192
       response = StreamingHttpResponse(
           FileWrapper(open(file_path, 'rb'), chunk_size),
           content_type="application/octet-stream"
       )
       response['Content-Length'] = os.path.getsize(file_path)    
       response['Content-Disposition'] = "attachment; filename=%s" % filename
       return response
    

    This will stream your file in chunks without loading it in memory; alternatively, you can use FileResponse,

    which is a subclass of StreamingHttpResponse optimized for binary files.

    0 讨论(0)
提交回复
热议问题