好吧,我有:谷歌應用程序引擎下載一個包含文件的文件
class Content(db.Model):
code=db.TextProperty()
而且還有存儲在數據庫中的代碼3個不同的值。我將如何創建一個zip文件,將三個代碼值存儲在三個可以下載的獨立文件中?
基於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)
你在代碼中使用unicode嗎?如果不是在寫入zipfile之前確保所有代碼都是ascii,請嘗試在writestr()中使用str(代碼)代替代碼 – Takahiro 2012-07-23 04:07:09
代碼包含用戶提交的Python代碼。 – areke 2012-07-23 04:28:06
嘗試[這](http://stackoverflow.com/questions/4542961/writing-unicode-to-binary-file-in-python) – Takahiro 2012-07-23 04:36:37