Kuberski - 酷伯司机

写在代码边上
随笔 - 57, 文章 - 1, 评论 - 213, 阅读 - 22万
  博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on   kuber  阅读(2328)  评论(3编辑  收藏  举报
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
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示