from functools import wraps from server.cache.base import get_cache from server.cache.key_getters import get_key_by_specification def cached( ttl: int, key: str = None, noself: bool = False, ): """Cache decorator. By default, (key=None) cache key is generated from function name and arguments. noself=True means that first argument of function will be excluded from cache key. """ def wrapper(f): @wraps(f) async def wrapped(*args, **kwargs): result = None cache_client = get_cache() cache_key = key or get_key_by_specification(f, args, kwargs, noself) if ttl > 0: result = await cache_client.get(cache_key) if result is None: result = await f(*args, **kwargs) await cache_client.set(cache_key, ttl, result) return result return wrapped return wrapper