2012-07-23 58 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

相關問題