cachetools_ttlchache.py 577 Bytes
import functools
import cachetools

cache = None


def async_ttl_cache(ttl: int = 900, maxsize: int = 20):
    global cache
    if cache is None:
        cache = cachetools.TTLCache(ttl=ttl, maxsize=maxsize)

    def decorator(fn):
        @functools.wraps(fn)
        async def memoize(*args, **kwargs):
            key = str((fn.__name__, args, kwargs))
            try:
                cache[key] = cache.pop(key)
            except KeyError:
                cache[key] = await fn(*args, **kwargs)
            return cache[key]

        return memoize

    return decorator