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 Cache(app=None, with_jinja2_ext=True, config=None)¶
This class is used to control the cache objects.
- init_app(app, config=None)¶
This is used to initialize cache with your app object
- property cache: SimpleCache¶
The backend instance the proxy methods delegate to. Use this to reach backend specific functionality that
Cachedoes not proxy. Requires an application context.
- get(*args, **kwargs)¶
Proxy function for internal cache object.
- has(*args, **kwargs)¶
Proxy function for internal cache object.
- set(*args, **kwargs)¶
Proxy function for internal cache object.
- add(*args, **kwargs)¶
Proxy function for internal cache object.
- delete(*args, **kwargs)¶
Proxy function for internal cache object.
- delete_many(*args, **kwargs)¶
Proxy function for internal cache object.
- get_many(*args, **kwargs)¶
Proxy function for internal cache object.
- set_many(*args, **kwargs)¶
Proxy function for internal cache object.
- get_dict(*args, **kwargs)¶
Proxy function for internal cache object.
- unlink(*args, **kwargs)¶
Proxy function for internal cache object only support Redis
- cached(timeout=None, key_prefix='view/%s', unless=None, forced_update=None, is_stale=None, response_filter=None, query_string=False, hash_method=None, cache_none=False, make_cache_key=None, source_check=None, response_hit_indication=False)¶
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
Outside of a request context, pass
pathto build the key for a givenrequest.pathand, forquery_string=True,query_argsto build the key for a given query string:key = view.make_cache_key( path="/works", query_args="limit=15&mock=true" ) cache.delete(key)
query_argsaccepts a query string, a mapping or an iterable of(key, value)pairs. Seedelete_cached()for the shorthand.
- Parameters:
timeout (int | timedelta | None) – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds. A
datetime.timedeltais also accepted and is rounded up to whole seconds.key_prefix (str | Callable[[], str]) –
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 (Callable[[...], Any] | None) – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely.
forced_update (Callable[[...], Any] | None) – 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.
is_stale (Callable[[...], Any] | None) – Default None. Called on a cache hit with the cached value as its first argument. If it is true the cached value will be recomputed. If the callable accepts more than one argument, the calls own arguments are passed after the cached value.
response_filter (Callable[[...], Any] | None) – 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 (bool) – 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.
cache_none (bool)
source_check (bool | None)
response_hit_indication (bool | None)
- Return type:
Changed in version 2.5.0: Include
key_prefixwhen building query string cache keys.- Parameters:
hash_method (Callable[[...], Any] | None) – Default None. If None will use the value set by
CACHE_HASH_METHOD, which defaults tohashlib.sha256. The hash method used to generate the keys for cached results.cache_none (bool) – 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 (Callable[[...], Any] | None) – Default None. If set to a callable object, it will be called to generate the cache key
source_check (bool | None) – 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 (bool | None) – Default False. If True, it will add to response header field ‘hit_cache’ if used cache.
query_string (bool)
- Return type:
Changed in version 2.5.0: A
werkzeug.exceptions.HTTPExceptionraised by the decorated function, for example through Flask’sabort(), is now cached like a returned response and re-raised on a cache hit. Useresponse_filter, which is given the exception’s response, to keep it out of the cache.
- delete_cached(f, path=None, query_args=None, **kwargs)¶
Delete the cached value of a
cached()decorated function.Example:
@app.route("/works") @cache.cached(query_string=True) def view_works(): return do_search(request.args) cache.delete_cached(view_works, "/works", {"limit": 15})
If you are calling this outside of a request context pass
pathand when the function was decorated withquery_string=Trueyou also have to passquery_args.- Parameters:
f (_CachedFunction[..., Any] | _BoundCachedFunction[Any, ..., Any]) – The decorated function whose cached value to delete.
path (str | None) – The
request.paththe value was cached for.query_args (str | Mapping[str, Any] | Iterable[tuple[str, Any]] | None) – The query string the value was cached for, as a query string, a mapping or an iterable of
(key, value)pairs. Only used when the function was decorated withquery_string=True.kwargs (Any) – The view arguments, passed to
url_for()to build the path whenpathis not given.
- Return type:
- memoize(timeout=None, make_name=None, unless=None, forced_update=None, is_stale=None, response_filter=None, hash_method=None, cache_none=False, source_check=None, args_to_ignore=None)¶
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 (int | timedelta | None) – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds. A
datetime.timedeltais also accepted and is rounded up to whole seconds.make_name (Callable[[...], str] | None) – 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 (Callable[[...], bool] | None) – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely.
forced_update (Callable[[...], bool] | None) – 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.
is_stale (Callable[[...], bool] | None) – Default None. Called on a cache hit with the cached value as its first argument. If it is true the cached value will be recomputed. If the callable accepts more than one argument, the calls own arguments are passed after the cached value.
response_filter (Callable[[...], Any] | None) – 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 (Callable[[...], Any] | None) – Default None. If
None, the value is set byCACHE_HASH_METHOD, which itself defaults tohashlib.sha256. The hash method used to generate the keys for cached results.cache_none (bool) – 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 (bool | None) – 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[str] | None) – 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.
- Return type:
Changelog
Added in version 1.10: params
args_to_ignoreAdded in version 0.5: params
make_name,unless
- delete_memoized(f, *args, **kwargs)¶
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
Arguments narrow the deletion down to a single call. A bound method supplies its own instance, so only the remaining arguments are given:
>>> cache.delete_memoized(adder1.add, 3)
When the function is reached through the class instead, the instance has to be passed explicitly, the same way a class is passed for a
@classmethod:>>> cache.delete_memoized(Adder.add, adder1, 3)
Changed in version 2.5.0: A bound method no longer needs to be given its own instance as the first argument. Passing it explicitly keeps working.
- Parameters:
- Return type:
None
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, *args)¶
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.
- class CachedResponse(response, timeout)¶
views wraped by @cached can return this (which inherits from flask.Response) to override the cache TTL dynamically
Signals¶
The following signals are supported:
- cache_view_hit¶
Sent when a view decorated with
cached()is served from the cache. It is passedcache, theCacheinstance,cache_key, the key the response was found under, andargsandkwargs, the arguments the view was called with.
- cache_view_miss¶
Sent when a view decorated with
cached()is not found in the cache and has to be called. It is passed the same arguments ascache_view_hit.
- cache_memoize_hit¶
Sent when a function decorated with
memoize()is served from the cache. In addition to the arguments passed tocache_view_hit, it is passedf, the undecorated function.
- cache_memoize_miss¶
Sent when a function decorated with
memoize()is not found in the cache and has to be called. It is passed the same arguments ascache_memoize_hit.
By default, signals are disabled. To enable sending signals set
CACHE_ENABLE_SIGNALS to True.
See the Flask documentation on signals for information on how to use these signals in your code.