我一直在使用一种提供下载的方法,但由于它不安全,我决定改变它。 (该方法是一个指向存储中原始文件的链接,但风险是每个知道该链接的人都可以下载该文件!)所以我现在通过我的 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/