...我有一个包含大量数据的 Django 应用程序和一个在 Raspberry Pi(操作系统 = Debian 12)上运行的 MariaDB 数据库。该应用程序使用 Daphne 作为 Web 服务器,因为其中还有 Django Channels 组件(Websocket)。现在我想实现一个备份功能,自动转储数据库,将转储与其他数据文件压缩在一起,并让浏览器自动下载 ZIP 文件。所以我做了一个下载视图:
def downbackup(request):
if request.user.is_superuser:
filename = '../temp/backup/backup.zip'
sourcefile = open(filename, 'rb')
return FileResponse(sourcefile)
else:
return(HttpResponse('No Access.'))
该视图是通过 url 从相关模板调用的,一切都很好。直到我们在现实生活中遇到大文件。在这种情况下(文件大小约为 6 GB),Daphne 立即停止运行,并且 Raspi 严重崩溃,以至于我必须打开和关闭电源。此外,在 Monitorix 中,我发现这些崩溃后内存消耗出现巨大峰值。但是 Daphne 日志、Django 日志(包括调试设置)和 Journalctl 中都没有错误消息。 Nginx(反向代理)报告上行链路超时 (504)。我想我从 Django 文档中了解到 FileResponse 缓冲文件以避免内存消耗,但这里一定有问题。有什么想法、建议吗?
您可以使用 Django 的
StreamingHttpResponse
代替 FileResponse
来高效处理大文件。
from django.http import StreamingHttpResponse
import os
def download_large_file(request):
# Path to the large file
file_path = '/path/to/your/large/file'
def file_iterator(file_path, chunk_size=8192):
with open(file_path, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
yield chunk
response = StreamingHttpResponse(file_iterator(file_path))
response['Content-Length'] = os.path.getsize(file_path)
return response