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

标签 python django permissions download

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

    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 所发布的,真正的解决方案是直接提供文件。

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

import os
import mimetypes

from wsgiref.util import FileWrapper

from django.http import StreamingHttpResponse


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"] = f"attachment; filename={filename}"
    return response

关于python - 在 Django 中提供大文件(高负载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8600843/

相关文章:

在 admin 中列出对象时的 django 预取

python - 没有名为 psycopg2 的模块

php - 同时更新同一台服务器上的数百个站点

python - 截断小数点前的值

python - 读取 YAML 文件并创建 Python 对象

python - 有没有办法将 View 函数转换为 celery 任务?

ios - NSCameraUsageDescription的使用说明

linux - 为 Web 文件夹分配权限的最佳做法

python - 有没有办法在 python 中监听 firebase 数据库的变化?

python - 如何在终止 Python 脚本时运行清理