How to give key_prefix, variable values while caching in Flask-Cache

1.2k Views Asked by At

We can cache any view/non-view function as

@cache.cached(timeout=50, key_prefix='all_comments')

Can we give key_prefix some variable values. Let say, I'm caching a function as

@cache.cached(timeout=50, key_prefix=value)
def get_all_comments(value):

Can we give key_prefix as the same arguments as we are getting in function. If not argument, then atleast some other variable by any proper way.

3

There are 3 best solutions below

0
On

In the docs it says

New in version 0.3.4: Can optionally be a callable which takes no arguments but returns a string that will be used as the cache_key.

1
On

Maybe what you are looking for is the @cache.memoize decorator that takes the function arguments as cache keys, giving you the opportunity to cache the function results for distinct values.

@cache.memoize(timeout=50)
def get_all_comments(value):

In this example, I'm caching for 50s.

0
On

You can use make_cache_key to provide a function for generating the key. The arguments of the cached function (i.e. get_all_comments) are passed as keyword arguments to the make_cache_key function.

def make_cache_key(**kwargs):
   return kwargs['value']

@cache.cached(timeout=50, make_cache_key=make_cache_key)
def get_all_comments(value):
   ....