FeedzShare的页面比较简单, 因此没有用Django等python web framework, 而是使用Google App Engine自带的webapp. 但是webapp没有内带页面缓存支持, 需要在每个action方法中自己检查缓存.
参考网上一些blogs, 我用decorator实现了一个简单的页面缓存机制, 类似asp.net中使用@ OutputCache指令一样, 用简单的声明来实现页面缓存. 如下面代码中, 页面将被被缓存5分钟:
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:
这个decorator现在还很简单, 目前页面缓存key统一用请求path+querystring (request.path_qs), 比如:
request.url=http://localhost/blog/article/1/, key = '/blog/article/1/'参考网上一些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?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
分类:
GAE&Python
标签:
appengine
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述