redis_cache_decorator.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目:Plog 作者: thundernet8 项目源码 文件源码
def redis_cached(timeout=None, key_prefix='view/%s', unless=None):
    """
    ?????????
    :param timeout: ??????, ????????3600?
    :param key_prefix: ???
    :param unless: ??????????
    :return: ???????????
    """
    def decorator(f):
        @functools.wraps(f)  # ??????
        def decorated_function(*args, **kwargs):
            if callable(unless) and unless() is True:
                return f(*args, **kwargs)

            if kwargs.get('nocache'):
                return f(*args, **kwargs)  # ????????? nocache ???????

            try:
                cache_key = decorated_function.make_cache_key(*args, **kwargs)
                cache_key = urllib.quote(cache_key, safe='')
                rv = redis_get(cache_key)
            except Exception:
                if current_app.debug:
                    raise
                return f(*args, **kwargs)

            if rv is None:
                rv = f(*args, **kwargs)
                try:
                    redis_set(cache_key, rv, timeout=decorated_function.cache_timeout)
                except Exception:
                    if current_app.debug:
                        raise
                    return f(*args, **kwargs)
            return rv

        def make_cache_key(*args, **kwargs):
            if callable(key_prefix):
                cache_key = key_prefix()
            elif '%s' in key_prefix:
                cache_key = key_prefix % (request.url+'_uid_'+str(current_user.get_id()))
            else:
                cache_key = key_prefix
            cache_key = hashlib.md5(cache_key.encode('utf-8')).hexdigest()
            cache_key = '_'.join((get_version(level='day'), cache_key))
            return cache_key

        decorated_function.uncached = f
        decorated_function.cache_timeout = timeout
        decorated_function.make_cache_key = make_cache_key

        return decorated_function
    return decorator
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号