Search code examples
pythonflaskmemoizationflask-cache

Setting Flask-Cache memoization value


If I have a function with the @cache.memoized decorator, is it possible to add a key-value pair to its caching without calling the function?


Solution

  • Yes. Looking at memoize in the Flask-Cache source, you can see the following code will let you set the cached return value for a function.

    from app import cache
    
    def set_memoized_cache(f, rv, *args, **kwargs):
        key = f.make_cache_key(f.uncached, *args, **kwargs)
        cache.set(key, rv, timeout=f.cache_timeout)
    

    Where f is the wrapped function whose cached values you want to change, rv is the return value you want to set, and *args and **kwargs are the arguments you'd like the caching to apply for.