Django响应包含一个包含多个csv文件的zip文件 [英] Django response that contains a zip file with multiple csv files
问题描述
我有一种算法,可以输出一个元组列表,准备将其写入csv文件中.
I have a algorithm that outputs a list of tuples which is ready to be written into a csv file.
我试图写3个csv文件(通过StringIO,所以不写磁盘),然后将它们全部压缩.之后,我要将其附加到Django请求的响应中.
I'm trying to write 3 csv files (through StringIO so no writing to disk) and then zip them altogether. After that I want to attach that to the response of a django request.
我不确定执行此操作最有效的方法是什么.我是否应该使用StringIO
通过我的算法存储3个电话?我应该在压缩文件之前先实际创建csv文件吗?我可以直接使用1个zipfile
呼叫,而无需调用3个StringIO
s的中间步骤吗?
I'm not sure what's the most efficient way to do this. Should I use StringIO
to store the 3 calls through my algo? Should I actually create the csv files first before zipping them? Can I directly use 1 zipfile
call without the intermediate steps of calling 3 StringIO
s?
谢谢
推荐答案
您可以执行以下操作:
# 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
You may want to use a StreamingHttpResponse
(or FileResponse ) if the file is big https://stackoverflow.com/a/48949959/1904584
这篇关于Django响应包含一个包含多个csv文件的zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!