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.

Parameters:
init_app(app, config=None)

This is used to initialize cache with your app object

Parameters:
Return type:

None

property cache: SimpleCache

The backend instance the proxy methods delegate to. Use this to reach backend specific functionality that Cache does not proxy. Requires an application context.

get(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

Any

has(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

bool

set(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

bool | None

add(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

bool

delete(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

bool

delete_many(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

list[str]

clear()

Proxy function for internal cache object.

Return type:

bool

get_many(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

list[Any]

set_many(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

list[Any]

get_dict(*args, **kwargs)

Proxy function for internal cache object.

Parameters:
Return type:

dict[str, Any]

Proxy function for internal cache object only support Redis

Parameters:
Return type:

list[str]

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 path to build the key for a given request.path and, for query_string=True, query_args to 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_args accepts a query string, a mapping or an iterable of (key, value) pairs. See delete_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.timedelta is 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.

  • hash_method (Callable[[...], Any] | None)

  • cache_none (bool)

  • make_cache_key (Callable[[...], Any] | None)

  • source_check (bool | None)

  • response_hit_indication (bool | None)

Return type:

Callable[[Callable[[~P], R]], _CachedFunction[~P, R]]

Changed in version 2.5.0: Include key_prefix when 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 to hashlib.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.

  • timeout (int | timedelta | None)

  • key_prefix (str | Callable[[], str])

  • unless (Callable[[...], Any] | None)

  • forced_update (Callable[[...], Any] | None)

  • is_stale (Callable[[...], Any] | None)

  • response_filter (Callable[[...], Any] | None)

  • query_string (bool)

Return type:

Callable[[Callable[[~P], R]], _CachedFunction[~P, R]]

Changed in version 2.5.0: A werkzeug.exceptions.HTTPException raised by the decorated function, for example through Flask’s abort(), is now cached like a returned response and re-raised on a cache hit. Use response_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 path and when the function was decorated with query_string=True you also have to pass query_args.

Parameters:
  • f (_CachedFunction[..., Any] | _BoundCachedFunction[Any, ..., Any]) – The decorated function whose cached value to delete.

  • path (str | None) – The request.path the 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 with query_string=True.

  • kwargs (Any) – The view arguments, passed to url_for() to build the path when path is not given.

Return type:

bool

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.timedelta is 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 by CACHE_HASH_METHOD, which itself defaults to hashlib.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:

Callable[[Callable[[~P], R]], _MemoizedFunction[~P, R]]

Changelog

Added in version 1.10: params args_to_ignore

Added 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:
  • fname – The memoized function.

  • *args (Any) – A list of positional parameters used with memoized function.

  • **kwargs (Any) – A dict of named parameters used with memoized function.

  • f (_MemoizedFunction[..., Any] | _BoundMemoizedFunction[Any, ..., Any])

  • *args

  • **kwargs

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_memoized is 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.

Parameters:
  • f (_MemoizedFunction[..., Any] | _BoundMemoizedFunction[Any, ..., Any])

  • args (Any)

Return type:

None

class CachedResponse(response, timeout)

views wraped by @cached can return this (which inherits from flask.Response) to override the cache TTL dynamically

Parameters:
make_template_fragment_key(fragment_name, vary_on=None)

Make a cache key for a specific fragment name.

Parameters:
Return type:

str

Signals

The following signals are supported:

cache_view_hit

Sent when a view decorated with cached() is served from the cache. It is passed cache, the Cache instance, cache_key, the key the response was found under, and args and kwargs, 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 as cache_view_hit.

cache_memoize_hit

Sent when a function decorated with memoize() is served from the cache. In addition to the arguments passed to cache_view_hit, it is passed f, 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 as cache_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.