Cache(timeout: int = 60 * 60, threshold: int = 100, *args, **kwargs)¶
This class is used to control the cache objects.
cached(self, timeout=None, key_prefix='view/%s', unless=None, forced_update=None, response_filter=None, query_string=False, hash_method=hashlib.md5, cache_none=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
# 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()
You MUST have a request context to actually called any functions that are cached.
New in version 0.4: The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable.
The original undecorated function
The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
A function used in generating the cache_key used.
timeout – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds.
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().
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.
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.
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.