python缓存机制

不支持异步
from functools import lru_cache
 @lru_cache(maxsize=128, typed=True)
 maxsize只使用最大缓存数,typed为True分类存储
 支持异步
 from async_lru import alru_cache
 @alru_cache()
 参数支持字典
 import functools
def hash_dict(func):
    """Transform mutable dictionnary
    Into immutable
    Useful to be compatible with cache
    """
    class HDict(dict):
        def __hash__(self):
            return hash(frozenset(self.items()))

    @functools.wraps(func)
    async def wrapped(*args, **kwargs):
        args = tuple([HDict(arg) if isinstance(arg, dict) else arg for arg in args])
        kwargs = {k: HDict(v) if isinstance(v, dict) else v for k, v in kwargs.items()}
        return await func(*args, **kwargs)
    return wrapped

猜你喜欢

转载自blog.csdn.net/weixin_43883907/article/details/86630274