我正在为我的Django网站上的报告应用程序工作.我想运行多个报告,并让每个报告在内存中生成一个.csv文件,可以批量下载为.zip.我想这样做而不将任何文件存储到磁盘.到目前为止,为了生成单个.csv文件,我遵循常见的操作:
mem_file = StringIO.StringIO()
writer = csv.writer(mem_file)
writer.writerow(["My content", my_value])
mem_file.seek(0)
response = HttpResponse(mem_file, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=my_file.csv'
Run Code Online (Sandbox Code Playgroud)
这很好,但只适用于单个解压缩的.csv.例如,如果我有一个使用StringIO流创建的.csv文件列表:
firstFile = StringIO.StringIO()
# write some data to the file
secondFile = StringIO.StringIO()
# write some data to the file
thirdFile = StringIO.StringIO()
# write some data to the file
myFiles = [firstFile, secondFile, thirdFile]
Run Code Online (Sandbox Code Playgroud)
我怎么能返回包含所有对象的压缩文件,myFiles并且可以正确解压缩以显示三个.csv文件?
我有这样的代码:
@login_required
def download_file(request):
content_type = "application/octet-stream"
download_name = os.path.join(DATA_ROOT, "video.avi")
with open(download_name, "rb") as f:
wrapper = FileWrapper(f, 8192)
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Disposition'] = 'attachment; filename=blabla.avi'
response['Content-Length'] = os.path.getsize(download_name)
# response['Content-Length'] = _file.size
return response
Run Code Online (Sandbox Code Playgroud)
似乎它有效。但是,如果我下载更大的文件(例如~600MB),我的内存消耗会增加 600MB。经过几次这样的下载后,我的服务器抛出:
内部服务器错误:/download/ 回溯(最近一次调用最后一次):
文件“/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/exception.py”,第 35 行,在内部响应 = get_response(request) 文件“/home/matous/. local/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/matous/.local/lib/ python3.5/site-packages/django/core/handlers/base.py”,第 126 行,在 _get_response 响应 =wrapped_callback(request, *callback_args, **callback_kwargs) 文件“/home/matous/.local/lib/python3 .5/site-packages/django/contrib/auth/decorators.py”,第 21 行,在 _wrapped_view 中返回 view_func(request, *args, **kwargs) 文件“/media/matous/89104d3d-fa52-4b14-9c5d- 9ec54ceebebb/home/matous/phd/emoapp/emoapp/mainapp/views.py",第 118 行,在 download_file …