好的,我有:
class Content(db.Model):
code=db.TextProperty()
数据库中存储了3种不同的代码值。我如何创建一个zip文件,将三个代码值存储在3个可下载的单独文件中?
根据eric.f的回答: 我重写了他的代码,使其能够做我想做的事情:
contents = db.GqlQuery("SELECT * FROM Content ORDER BY created DESC")
output = StringIO.StringIO()
with zipfile.ZipFile(output, 'w') as myzip:
for content in contents:
if content.code:
code=content.code
else:
code=content.code2
myzip.writestr('udacity_code'+`content.key().id()`, code)
self.response.headers["Content-Type"] = "application/zip"
self.response.headers['Content-Disposition'] = "attachment; filename=test.zip"
self.response.out.write(output.getvalue())
我收到了错误...
self.response.out.write(output.getvalue(), "utf-8")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/StringIO.py", line 270, in getvalue
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb4 in position 10: ordinal not in range(128)
答案 0 :(得分:1)
import zipfile
import StringIO
output = StringIO.StringIO()
with zipfile.ZipFile(output, 'w') as myzip:
myzip.writestr('file1.txt', 'aaaaaaaaa')
myzip.writestr('file2.txt', 'bbbbbbbbb')
myzip.writestr('file3.txt', 'ccccccccc')
然后进行回复,将output.getvalue()
设置为内容,并设置标题如下:
Content-type: application/zip
Content-disposition: attachment; filename=test.zip