我应该使用memcache吗?

时间:2011-04-17 07:05:00

标签: python google-app-engine kmz

我的代码从Google App Engine生成zip file,用于在浏览器中加载,即10 KB<尺寸< 1000 KB,我想知道我是否可以在这里使用memcache,或者文件是否太大或已经缓存。我已经使用了memcache并在首先生成实际文件时设置了缓存控制。

class KMZHandler(webapp.RequestHandler):
    def add_file(self, zip_file, url, file_name):
        """Fetch url, and add content as file_name to the zip file."""
        result = urlfetch.fetch(url)
        if not result.content:
            return
        zip_file.writestr(file_name, result.content)

    def get(self):
        """Attempt to create a zip file."""
        # you could set 'count' like this:
        # count = int(self.request.get('count', 1000))

        zipstream = StringIO.StringIO()
        zip_file = zipfile.ZipFile(zipstream, "w")

        # repeat this for every URL that should be added to the zipfile
        url = 'http://www.koolbusiness.com/list.kml'
        self.add_file(zip_file, url, "list.kml")

        # we have finished with the zip so package it up and write the directory
        zip_file.close()

        # set the headers...

        self.response.headers["Cache-Control"] = "public,max-age=%s" % 86400
        self.response.headers['Content-Type'] ='application/zip'
        self.response.headers['Content-Disposition'] = 'attachment;filename="list.kmz"'

        # create and return the output stream
        zipstream.seek(0)
        self.response.out.write(zipstream.read())
        zipstream.close()

以下是使用memcache并创建实际文件的部分:

class KMLHandler(webapp.RequestHandler):
 def get(self):   
    self.response.headers["Cache-Control"] = "public,max-age=%s" % 86400
    start=datetime.datetime.now()-timedelta(days=20)
    count = int(self.request.get('count')) if not self.request.get('count')=='' else 1000        
    from google.appengine.api import memcache
    memcache_key = "ads"
    data = memcache.get(memcache_key)
    if data is None:
      a= Ad.all().filter("modified >", start).filter("url IN", ['www.koolbusiness.com']).filter("published =", True).order("-modified").fetch(count)
      memcache.set("ads", a)  
    else:
      a = data
    dispatch='templates/kml.html'
    template_values = {'a': a , 'request':self.request,}
    path = os.path.join(os.path.dirname(__file__), dispatch)
    output = template.render(path, template_values)
    self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
    self.response.headers['Content-Length'] = len(output)
    self.response.out.write(output)

感谢您的回答

1 个答案:

答案 0 :(得分:2)

如果文件是under 1mb,并且每个请求都没有更改,那么memcaching KMZ可能会减少资源使用。

KMZ文件尚未在memcache中,但它可能位于前端缓存中。您在生成KML时会记录查询的结果(有关how to memcache entities的说明,请参阅Nick的博客),但缓存不会考虑countstart的不同值。如果不重要,您也可以考虑直接记忆KML(或KMZ)文件;如果 重要,你就需要修复缓存策略。