简体   繁体   English

如何在Google App Engine(python)中创建csvs并写入zip文件?

[英]how to create csvs and write to zip file in Google App Engine (python)?

I'm trying to write multiple csvs to a zip file in Google App Engine. 我正在尝试将多个csv写入Google App Engine中的zip文件。 I found this post: Confused about making a CSV file into a ZIP file in django which has been helpful. 我发现了这篇文章: 对将CSV文件转换为django中的ZIP文件感到困惑,这很有帮助。 In fact, when I do: 实际上,当我这样做时:

o=StringIO.StringIO()
file = zipfile.ZipFile(file=o,compression=zipfile.ZIP_DEFLATED,mode="w")
.. . ## add your csv files here
file.close()
o.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="your_csvs.zip"'
self.response.out.write(o.getvalue())

I get a blank zip file which is fine. 我得到一个空白的zip文件,很好。 However, above this, I have 但是,在此之上,我有

self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=sheet.csv'
writer = csv.writer(self.response.out)
writer.writerow(['Text Here'])

Which by itself lets me download a csv. 它本身可以让我下载csv。 Where I'm stuck is when I try to combine the two. 当我尝试将两者结合在一起时,我会陷入困境。 If I do: 如果我做:

self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=sheet.csv'
writer = csv.writer(self.response.out)
writer.writerow(['Text Here'])

o=StringIO.StringIO()
file = zipfile.ZipFile(file=o,compression=zipfile.ZIP_DEFLATED,mode="w")
file.writestr("sheet.csv", output.getvalue())
file.close()
o.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="your_csvs.zip"'
self.response.out.write(o.getvalue())

I get a zipfile that can't open. 我得到一个无法打开的zip文件。 I'm fairly certain I'm using writestr incorrectly but I can't figure out the code to get the csv I create into the zip. 我可以肯定我使用了错误的writestr,但是我无法弄清楚将要创建的csv放入zip的代码。 Can anyone help? 有人可以帮忙吗?

Here is what I am doing 这是我在做什么

        zh = StringIO()
        zf = zipfile.ZipFile(zh,'w')
        zi = zipfile.ZipInfo('test.csv')
        zi.compress_type = zipfile.ZIP_DEFLATED
        zi.comment = 'Some comment'
        zf.writestr(zi, zh.getvalue())
        zf.close()
        payload = zh.getvalue()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM