API¶
This section contains the API documentation of the Flask-Caching extension and lists the backends which are supported out of the box via cachelib. The Configuration section explains how the backends can be used.
Cache API¶
- class flask_caching.Cache(app: Flask | None = None, with_jinja2_ext: bool = True, config=None)¶
This class is used to control the cache objects.
- get_many(*args, **kwargs)¶
Proxy function for internal cache object.
- cached(timeout: int | None = None, key_prefix: str = 'view/%s', unless: Callable | None = None, forced_update: Callable | None = None, response_filter: Callable | None = None, query_string: bool = False, hash_method: Callable = <built-in function openssl_md5>, cache_none: bool = False, make_cache_key: Callable | None = None, source_check: bool | None = None, response_hit_indication: bool | None = False) Callable¶
Decorator. Use this to cache a function. By default the cache key is view/request.path. You are able to use this decorator with any function by changing the key_prefix. If the token %s is located within the key_prefix then it will replace that with request.path
Example:
# An example view function @cache.cached(timeout=50) def big_foo(): return big_bar_calc() # An example misc function to cache. @cache.cached(key_prefix='MyCachedList') def get_list(): return [random.randrange(0, 1) for i in range(50000)] my_list = get_list()
Note
You MUST have a request context to actually called any functions that are cached.
Changelog
Added in version 0.4: The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable.
- uncached
The original undecorated function
- cache_timeout
The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
- make_cache_key
A function used in generating the cache_key used.
readable and writable
- Parameters:
timeout – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds.
key_prefix –
Default ‘view/%(request.path)s’. Beginning key to . use for the cache key. request.path will be the actual request path, or in cases where the make_cache_key-function is called from other views it will be the expected URL for the view as generated by Flask’s url_for().
Changelog
Added 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.
unless – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely.
forced_update – Default None. If this callable is true, cache value will be updated regardless cache is expired or not. Useful for background renewal of cached functions.
response_filter – Default None. If not None, the callable is invoked after the cached function evaluation, and is given one argument, the response content. If the callable returns False, the content will not be cached. Useful to prevent caching of code 500 responses.
query_string – Default False. When True, the cache key used will be the result of hashing the ordered query string parameters. This avoids creating different caches for the same query just because the parameters were passed in a different order. See _make_cache_key_query_string() for more details.
hash_method – Default hashlib.md5. The hash method used to generate the keys for cached results.
cache_none – Default False. If set to True, add a key exists check when cache.get returns None. This will likely lead to wrongly returned None values in concurrent situations and is not recommended to use.
make_cache_key – Default None. If set to a callable object, it will be called to generate the cache key
source_check – Default None. If None will use the value set by CACHE_SOURCE_CHECK. If True, include the function’s source code in the hash to avoid using cached values when the source code has changed and the input values remain the same. This ensures that the cache_key will be formed with the function’s source code hash in addition to other parameters that may be included in the formation of the key.
response_hit_indication – Default False. If True, it will add to response header field ‘hit_cache’ if used cache.
- memoize(timeout: int | None = None, make_name: Callable | None = None, unless: Callable | None = None, forced_update: Callable | None = None, response_filter: Callable | None = None, hash_method: Callable = <built-in function openssl_md5>, cache_none: bool = False, source_check: bool | None = None, args_to_ignore: Any | None = None) Callable¶
Use this to cache the result of a function, taking its arguments into account in the cache key.
Information on Memoization.
Example:
@cache.memoize(timeout=50) def big_foo(a, b): return a + b + random.randrange(0, 1000)
>>> big_foo(5, 2) 753 >>> big_foo(5, 3) 234 >>> big_foo(5, 2) 753
Changelog
Added in version 0.4: The returned decorated function now has three function attributes assigned to it.
- uncached
The original undecorated function. readable only
- cache_timeout
The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
readable and writable
- make_cache_key
A function used in generating the cache_key used.
readable and writable
- Parameters:
timeout – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds.
make_name – Default None. If set this is a function that accepts a single argument, the function name, and returns a new string to be used as the function name. If not set then the function name is used.
unless – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely.
forced_update – Default None. If this callable is true, cache value will be updated regardless cache is expired or not. Useful for background renewal of cached functions.
response_filter – Default None. If not None, the callable is invoked after the cached funtion evaluation, and is given one arguement, the response content. If the callable returns False, the content will not be cached. Useful to prevent caching of code 500 responses.
hash_method – Default hashlib.md5. The hash method used to generate the keys for cached results.
cache_none – Default False. If set to True, add a key exists check when cache.get returns None. This will likely lead to wrongly returned None values in concurrent situations and is not recommended to use.
source_check – Default None. If None will use the value set by CACHE_SOURCE_CHECK. If True, include the function’s source code in the hash to avoid using cached values when the source code has changed and the input values remain the same. This ensures that the cache_key will be formed with the function’s source code hash in addition to other parameters that may be included in the formation of the key.
args_to_ignore – List of arguments that will be ignored while generating the cache key. Default to None. This means that those arguments may change without affecting the cache value that will be returned.
Added in version 1.10: params
args_to_ignoreChangelog
Added in version 0.5: params
make_name,unless
- delete_memoized(f, *args, **kwargs) None¶
Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all versions of the caches will be forgotten.
Example:
@cache.memoize(50) def random_func(): return random.randrange(1, 50) @cache.memoize() def param_func(a, b): return a+b+random.randrange(1, 50)
>>> random_func() 43 >>> random_func() 43 >>> cache.delete_memoized(random_func) >>> random_func() 16 >>> param_func(1, 2) 32 >>> param_func(1, 2) 32 >>> param_func(2, 2) 47 >>> cache.delete_memoized(param_func, 1, 2) >>> param_func(1, 2) 13 >>> param_func(2, 2) 47
Delete memoized is also smart about instance methods vs class methods.
When passing a instancemethod, it will only clear the cache related to that instance of that object. (object uniqueness can be overridden by defining the __repr__ method, such as user id).
When passing a classmethod, it will clear all caches related across all instances of that class.
Example:
class Adder(object): @cache.memoize() def add(self, b): return b + random.random()
>>> adder1 = Adder() >>> adder2 = Adder() >>> adder1.add(3) 3.23214234 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(adder1.add) >>> adder1.add(3) 3.01348673 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(Adder.add) >>> adder1.add(3) 3.53235667 >>> adder2.add(3) 3.72341788
- Parameters:
fname – The memoized function.
*args – A list of positional parameters used with memoized function.
**kwargs – A dict of named parameters used with memoized function.
Note
Flask-Caching uses inspect to order kwargs into positional args when the function is memoized. If you pass a function reference into
fname, Flask-Caching will be able to place the args/kwargs in the proper order, and delete the positional cache.However, if
delete_memoizedis just called with the name of the function, be sure to pass in potential arguments in the same order as defined in your function as args only, otherwise Flask-Caching will not be able to compute the same cache key and delete all memoized versions of it.Note
Flask-Caching maintains an internal random version hash for the function. Using delete_memoized will only swap out the version hash, causing the memoize function to recompute results and put them into another key.
This leaves any computed caches for this memoized function within the caching backend.
It is recommended to use a very high timeout with memoize if using this function, so that when the version hash is swapped, the old cached results would eventually be reclaimed by the caching backend.
- delete_memoized_verhash(f: Callable, *args) None¶
Delete the version hash associated with the function.
Warning
Performing this operation could leave keys behind that have been created with this version hash. It is up to the application to make sure that all keys that may have been created with this version hash at least have timeouts so they will not sit orphaned in the cache backend.
Backends¶
Changed in version 1.11.0: flask-caching now uses cachelib as backend. See cachelib API for further details.