zoukankan      html  css  js  c++  java
  • 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
    ")
    print(r.get("t1"))    #b'adsafa
    '
    
    r.set("t2",["adsafa
    "])
    print(r.get("t2"))    #b"['adsafa\n']"

    r2 = eval(r.get("t2"))
    print(r2)          #['adsafa ']列表类型,任然需要使用[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)
  • 相关阅读:
    Log4Net 自定义级别,分别记录到不同的文件中
    带着忧伤,寻觅快乐
    程序员进阶学习书籍
    PHP编码技巧
    PHP精度问题
    Laravel5 构造器高级查询条件写法
    正则表达式 /i /g /m /ig /gi
    MySQL运算符的优先级
    PHP获取当前页面完整路径URL
    使用ssl模块配置同时支持http和https并存
  • 原文地址:https://www.cnblogs.com/ssyfj/p/8608650.html
Copyright © 2011-2022 走看看