2012-02-03 105 views
1

我正在使用AppEngine在我的應用中存儲一些pickled python對象。我想直接向用戶提供這些信息,並且我只是使用X-AppEngine-Blobkey標題將文件以file.pickle.gz文件名提供給用戶。但是,當我嘗試使用簡單的雙擊將我的計算機(Mac OS)提取這些文件時,這些文件將變成file.pickle.gz.cpgzAppengine提供gzip壓縮文件

我認爲這是我的瀏覽器是偷偷摸摸的,並提取它們,但我不這麼認爲,因爲

pickle.load('file.pickle.gz') 

不行的,而且也不

pickle.load('file.pickle.gz.cpgz') 

要存儲文件,我用:

blobfile = files.blobstore.create(mime_type='application/gzip') 
    with files.open(blobfile, 'a') as f: 
     gz = gzip.GzipFile(fileobj=f,mode='wb') 
     gz.write(my_pickled_object) 
     gz.close() 
    files.finalize(blobfile) 

我想我不理解gzips的工作方式。有人可以解釋嗎?

回答

1

您確定file.pickle.gz.cpgz是您雙擊下載的file.pickle.gz文件的結果嗎?通常「.cpgz」是一種不同類型的存檔文件。

我可以獲取您在發佈服務器上發佈的代碼,而無需進行重大更改。這裏的代碼,如果有幫助的話:

#!/usr/bin/env python 

from __future__ import with_statement 
import gzip 
import pickle 
from google.appengine.api import files 
from google.appengine.api import memcache 
from google.appengine.ext import blobstore 
from google.appengine.ext import webapp 
from google.appengine.ext.webapp import blobstore_handlers 
from google.appengine.ext.webapp import util 

class MainHandler(webapp.RequestHandler): 
    def get(self): 
     self.response.out.write('Hello world! <a href="/make">make</a> <a href="/get">get</a>') 

class MakeFileHandler(webapp.RequestHandler): 
    def get(self): 
     data = pickle.dumps({'a':1, 'b':True, 'c':None}) 

     blobfile = files.blobstore.create(mime_type='application/gzip') 
     with files.open(blobfile, 'a') as f: 
      gz = gzip.GzipFile(fileobj=f,mode='wb') 
      gz.write(data) 
      gz.close() 
     files.finalize(blobfile) 
     memcache.set('filekey', files.blobstore.get_blob_key(blobfile)) 
     self.redirect('/') 

class GetFileHandler(blobstore_handlers.BlobstoreDownloadHandler): 
    def get(self): 
     blobkey = memcache.get('filekey') 
     if blobkey: 
      self.send_blob(blobkey) 
     else: 
      self.response.out.write('No data key set <a href="/">back</a>') 

def main(): 
    application = webapp.WSGIApplication([('/', MainHandler), 
              ('/make', MakeFileHandler), 
              ('/get', GetFileHandler)], 
             debug=True) 
    util.run_wsgi_app(application) 

if __name__ == '__main__': 
    main() 

點擊「make」,然後點擊「get」。名爲「get.gz」的文件會下載到您的~/Downloads/文件夾中(至少在Chrome中)。雙擊它以生成一個名爲「get」的文件。然後:

% python 
>>> import pickle 
>>> pickle.load(open('get')) 
{'a': 1, 'c': None, 'b': True} 
+1

你是對的,我的代碼工作。 「您是否嘗試關閉並再次打開?」。 – noio 2012-02-04 11:53:16