2012-07-23 55 views
0

好吧,我有:谷歌应用程序引擎下载一个包含文件的文件

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) 
+0

你在代码中使用unicode吗?如果不是在写入zipfile之前确保所有代码都是ascii,请尝试在writestr()中使用str(代码)代替代码 – Takahiro 2012-07-23 04:07:09

+0

代码包含用户提交的Python代码。 – areke 2012-07-23 04:28:06

+0

尝试[这](http://stackoverflow.com/questions/4542961/writing-unicode-to-binary-file-in-python) – Takahiro 2012-07-23 04:36:37

回答

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 
+0

你可以看看我的代码,看看你是否知道做什么? (content.code和content.code2的值是格式化的Python代码)我真的需要你的帮助...谢谢! – areke 2012-07-23 03:44:28

+0

谢谢...我明白了! – areke 2012-07-23 05:52:13

相关问题