Caching
The Caching API provides a simple interface for caching objects with multiple storage strategies.
Basic Usage
>>> from canvas_core import caching
# Get the Cache client.
>>> cache = caching.get_cache()
# Fetch a given key from the cache.
>>> cache.get("my_cache_key")
# Set a value in the cache.
>>> cache.set("my_cache_key", "my_value")
# Delete a key from the cache.
>>> cache.delete("my_cache_key")
# Check if the key exists in the cache
>>> "my_cache_key" in cache
# Delete the entire cache
>>> cache.clear()
# Delete the contents of all configured caches.
>>> caching.clear_caches()
API Reference
- class canvas_core.caching.Cache(connection: BaseCache, prefix: str = '')
A Class wrapper for interacting with cache.
- clear() None
Remove all values from the cache at once.
- delete(key: str) None
Delete a key from the cache.
- Parameters:
key – The key to be removed from the cache.
- get(key: str, default: Any | None = None) Any
Fetch a given key from the cache.
- Parameters:
key – The cache key.
default – The value to return if the key does not exist.
- Returns:
The cached value, or the default if the key does not exist.
- get_many(keys: Iterable[str]) Any
Fetch multiple values from the cache.
This is often much faster than retrieving cached values individually, and its use is encouraged where possible.
- Parameters:
keys – The cache keys to retrieve.
- Returns:
A dict mapping each key in ‘keys’ to its cached value.
- get_or_set(key: str, default: Any | None = None, timeout: int | None = None) Any
Fetch a given key from the cache, or set it to the given default.
If the key does not exist, it will be created with the given default as its value. If the default is a callable, it will be called with no arguments and the return value will be used.
- Parameters:
key – The key to retrieve.
default – The default value to set if the key does not exist. May be a callable with no arguments.
timeout – The number of seconds for which to cache the key.
- Returns:
The cached value.
- set(key: str, value: Any, timeout: int | None = None) None
Set a value in the cache.
- Parameters:
key – The cache key.
value – The value to cache.
timeout – The number of seconds for which the value should be cached.
- set_many(data: dict[str, Any], timeout: int | None = None) list[str]
Set multiple values in the cache simultaneously.
- Parameters:
data – A dict of cache keys and their values.
timeout – The number of seconds for which to cache the data.
- Returns:
Returns a list of cache keys that failed insertion if supported by the backend. Otherwise, an empty list is returned.
- exception canvas_core.caching.CacheConfigurationError(driver: str, *args: Any)
An Exception raised when cache driver doesn’t exist.
- canvas_core.caching.clear_caches(drivers: list[str] | None = None) None
Clear caches.
Clears all caches when called with no arguments. If a list of drivers is passed, only those caches will be cleared.
- Parameters:
drivers – The list of caches to be cleared.