包含带有多个 csv 文件的 zip 文件的 Django 响应

JCh*_*hao 1 python django zipfile stringio

我有一个算法可以输出一个元组列表,该列表已准备好写入 csv 文件。

我正在尝试写入 3 个 csv 文件(通过 StringIO,因此不写入磁盘),然后将它们完全压缩。之后,我想将其附加到 django 请求的响应中。

我不确定这样做的最有效方法是什么。我应该StringIO用来通过我的算法存储 3 个调用吗?在压缩它们之前,我应该先创建 csv 文件吗?我可以直接使用 1 zipfilecall 而不需要调用 3 StringIOs的中间步骤吗?

谢谢

tri*_*het 5

您可以执行以下操作:

# Create the zip file
output = StringIO.StringIO()
f = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED)
f.writestr('first.csv', '<the content of first.csv>')
f.writestr('second.csv', '<the content of second.csv>')
f.writestr('third.csv', '<the content of third.csv>')
f.close()
# Build your response
response = HttpResponse(output.getvalue(), mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename="yourzipfilename.zip"'
return response
Run Code Online (Sandbox Code Playgroud)

如果文件很大,您可能需要使用StreamingHttpResponse(或FileResponse/sf/answers/3426497161/