Serving large files ( with high loads ) in Django

前端 未结 5 1336
耶瑟儿~
耶瑟儿~ 2020-12-04 13:00

I\'ve been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk

5条回答
  •  余生分开走
    2020-12-04 13:25

    FileWrapper won't work when GZipMiddleware is installed (Django 1.4 and below): https://code.djangoproject.com/ticket/6027

    If using GZipMiddleware, a practical solution is to write a subclass of FileWrapper like so:

    from wsgiref.util import FileWrapper
    class FixedFileWrapper(FileWrapper):
        def __iter__(self):
            self.filelike.seek(0)
            return self
    
    import mimetypes, os
    my_file = '/some/path/xy.ext'
    response = HttpResponse(FixedFileWrapper(open(my_file, 'rb')), content_type=mimetypes.guess_type(my_file)[0])
    response['Content-Length'] = os.path.getsize(my_file)
    response['Content-Disposition'] = "attachment; filename=%s" % os.path.basename(my_file)
    return response
    

    As of Python 2.5, there's no need to import FileWrapper from Django.

提交回复
热议问题