我有一个算法可以输出准备写入 csv 文件的元组列表。
我正在尝试写入 3 个 csv 文件(通过 StringIO,因此不写入磁盘),然后将它们全部压缩。之后,我想将其附加到 Django 请求的响应中。
我不确定执行此操作的最有效方法是什么。我应该使用 StringIO 通过我的算法存储 3 个调用吗?我应该在压缩之前先创建 csv 文件吗?我可以直接使用 1 个 zipfile 调用而无需调用 3 个 StringIO 的中间步骤吗?
谢谢
请您参考如下方法:
你可以这样做:
# 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
如果文件很大,您可能需要使用 StreamingHttpResponse(或 FileResponse )https://stackoverflow.com/a/48949959/1904584
