小编典典

在Django中提供大文件(高负载)

django

我一直在使用一种提供下载服务的方法,但是由于它不安全,所以我决定对此进行更改。(该方法是到存储中原始文件的链接,但是风险是每个知道链接的人都可以下载该文件!)因此,我现在通过我的视图提供文件,这样,只有拥有权限的用户才能下载文件,但是我注意到服务器上的负载很高,同时有许多文件同时下载请求。这是我为用户处理下载的代码的一部分(考虑文件是图像)

    image = Image.open ("the path to file")
    response = HttpResponse(mimetype = 'image/png' )
    response['Content-Disposition'] = 'attachment: filename=%s.png' % filename
    image.save(response , "png")
    return response 

在保持安全性并降低服务器端负载的情况下,有没有更好的方法来提供文件?提前致谢


阅读 616

收藏
2020-04-02

共1个答案

小编典典

打开图像会将其加载到内存中,这就是导致大量使用情况下负载增加的原因。正如Martin所说,真正的解决方案是直接提供文件。

这是另一种方法,它将以分块方式流式传输文件而不将其加载到内存中。

import os
import mimetypes
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper


def download_file(request):
   the_file = '/some/file/name.png'
   filename = os.path.basename(the_file)
   chunk_size = 8192
   response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size),
                           content_type=mimetypes.guess_type(the_file)[0])
   response['Content-Length'] = os.path.getsize(the_file)    
   response['Content-Disposition'] = "attachment; filename=%s" % filename
   return response
2020-04-02