python---redis缓存页面实现
import tornado.web from controllers.BaseController import BaseRequestHandler import redis pool = redis.ConnectionPool(host="localhost",port=6379) r = redis.Redis(connection_pool=pool) class IndexHandler(tornado.web.RequestHandler): def flush(self, include_footers=False, callback=None): self._data_html = self._write_buffer super(IndexHandler,self).flush(include_footers,callback) def get(self, *args, **kwargs): ret =r.get('index') print(ret) if ret: self.write(str) return import time tm = time.time() self.render('home/index.html',time=tm) r.set('index',self._data_html[0],ex=10)#设置过期时间为10秒
其中注意:
r.set('index',self._data_html[0],ex=10)#设置过期时间为10秒
由于获取的self._data_html数据是列表,redis对于处理str,bytes之外的其他数据会进行转义为str来保存,所以我们可以直接取出数据_data_html中的str数据self._data_html[0]就是str数据,可以保存redis,直接取出使用即可
数据转义测试:
r.set('t1',"adsafa\n") print(r.get("t1")) #b'adsafa\n' r.set("t2",["adsafa\n"])
print(r.get("t2")) #b"['adsafa\\n']"
r2 = eval(r.get("t2"))
print(r2) #['adsafa\n']列表类型,任然需要使用[0]获取数据
页面缓存,也可以使用文件缓存,像是thinkphp中默认是使用文件缓存数据
装饰器实现:
import tornado.web from controllers.BaseController import BaseRequestHandler import redis pool = redis.ConnectionPool(host="localhost",port=6379) r = redis.Redis(connection_pool=pool) def cache(func): def inner(self,*args,**kwargs): ret = r.get('index') if ret: self.write(ret) return func(self,*args,**kwargs) r.set('index', self._data_html[0], ex=10) # 设置过期时间为10秒 return inner class IndexHandler(tornado.web.RequestHandler): def flush(self, include_footers=False, callback=None): self._data_html = self._write_buffer super(IndexHandler,self).flush(include_footers,callback) @cache def get(self, *args, **kwargs): import time tm = time.time() self.render('home/index.html',time=tm)