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

    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  

在保证安全性和降低服务器端负载的同时,有没有更好的方法来提供文件?

推荐答案

您打开的图像会将其加载到内存中,这就是在大量使用的情况下会导致负载增加的原因.正如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

Django相关问答推荐

当RST =True时RST CSS

使用override_sets构建一个预装饰的类,以更快的客户端.登录?

如何显示日期?

在模板中自动添加变量

模仿没有像预期的那样工作(Django)

在Django中提交表单后更改模型数据

在生成的表单元素处出现多值DictKeyError

在 Django 中重组多对多字段

data._mutable= 在 Django REST 框架中为真

在用例图中建模前端和后端

组织大型 Django 元素的指南

在 PyCharm 中运行 Django 测试

直接在模型类上使用 Django 管理器与静态方法

base.html 中的 Django 变量

django 有条件地过滤对象

在 Django 中使用 AuthenticationForm

Django - 来自 QuerySet 的唯一列表

过滤 Django 数据库中包含数组中任何值的字段

Django:按位置排序,忽略 NULL

防止 django 管理员转义 html