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)