现在的位置: 首页 > 综合 > 正文

用decorator在Google App Engine中实现页面缓存

2011年07月15日 ⁄ 综合 ⁄ 共 1463字 ⁄ 字号 评论关闭

FeedzShare的页面比较简单, 因此没有用Django等python web framework, 而是使用Google App Engine自带的webapp. 但是webapp没有内带页面缓存支持, 需要在每个action方法中自己检查缓存.
参考网上一些blogs, 我用decorator实现了一个简单的页面缓存机制, 类似asp.net中使用@ OutputCache指令一样, 用简单的声明来实现页面缓存. 如下面代码中, 页面将被被缓存5分钟:

from cacheHelper import cachedPage
from datetime import datetime
class
MyHandler(webapp.RequestHandler):
@cachedPage(time=60*5)
  def get(self):
   
return "<html><body><p>%s</p></body></html>" % datetime.utcnow()

decorator代码:


def cachedPage(time=60):

  """Decorator to cache pages in memcache with path_qs used as key."""
  from google.appengine.ext import webapp
  def decorator(fxn):
    def wrapper(*args, **kwargs):
      requestHandler = args[0]
      key = requestHandler.request.path_qs
      data = memcache.get(key)
      if data is None:
        data = fxn(*args, **kwargs)
        memcache.set(key, data, time)
      return requestHandler.response.out.write(data)
    return wrapper
  return decorator

time参数是以秒计的缓存时间, time=0时页面被缓存一直到下次在memcache清理缓存前. 使用很简单, 只需要在RequestHandler中声明一下, 并且在方法中返回需要缓存的html:

  def get(self):
   
return "<html><body><p>%s</p></body></html>" % datetime.utcnow()

这个decorator现在还很简单, 目前页面缓存key统一用请求path+querystring (request.path_qs), 比如:

    request.url=http://localhost/blog/article/1/,        key = '/blog/article/1/'
    request.url= http://localhost/blog/article?id=1,   key = '/blog/article?id=1'
如果你有更复杂的场景, 可以自己扩充. asp.net的page cache中按language, browser, header等缓存, 都可以参考WebOb文档来实现.


参考:
Decorator to get/set from the memcache automatically
Decorator for Memcache Get/Set in python
Python中的decorator(limodou)
WebOb Reference
 

kuber @FeedzShare

抱歉!评论已关闭.