JEFFREY

feiworks.com

tornado缓存

class CacheBaseHandler(tornado.web.RequestHandler):
  
    def prepare(self):
        # 这里判断一下是否是GET请求,是否是非登陆用户,才做以下处理
        cached = self.application.db.cache.find_one({"slug": self.request.path})
        if cached is not None:
            self.write(cached["content"])
            self.finish()
  
    def render_string(self, template_name, **kwargs):
        html_generated = \
            super(CacheBaseHandler, self).render_string(template_name, **kwargs)
        self.application.db.cache.update({"slug": self.request.path},
            {"$set": {"content": html_generated}},
            upsert=True)
 
        return html_generated
 
    def on_finish(self):
        """ 重写结束请求前的方法函数 """
        if self.request.method == "POST":
            # 如果遇到POST提交则清空缓存
            self.application.db.cache.remove({"slug": self.request.path})


发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-BlogPHP 1.5 Zero

Copyright @ 2014-2019 All Rights Reserved.
feiworks.com