Skip to content

API

CacheInterface

Protocol class for the cache interface required by Slycache

get

get(key: str, default: Optional[Any] = None) -> Any

Get a value from the cache and return it or else the default value.

Parameters:

Name Type Description Default
key str

the cache key

required
default Optional[Any]

value to return if no value found in the cache

None

Returns:

Name Type Description
any Any

the cache value or default

set

set(key: str, value: Any, timeout: Optional[int] = None)

Set a value in the cache with the given key and timeout.

Parameters:

Name Type Description Default
key str

the cache key

required
value Any

the cache value

required
timeout Optional[int]

cache item timeout in seconds or None

None

delete

delete(key: str)

Delete value from cache.

Parameters:

Name Type Description Default
key str

the key to delete

required

KeyGenerator

Protocol for a key generator class.

validate

validate(template: str, func: Callable)

Validate a key template.

Parameters:

Name Type Description Default
template str

key template

required
func Callable

the decorated function

required

Raises:

Type Description
ValueError

if the template is not validated

generate

generate(
    namespace: Optional[str],
    template: str,
    func: Callable,
    call_args: Dict,
) -> str

Generate a key for use in a cache operation.

Parameters:

Name Type Description Default
namespace Optional[str]

the namespace to suffix the key with

required
template str

the key template

required
func Callable

the decorated function

required
call_args Dict

dictionary of arguments that were used in the function invocation

required

Returns:

Name Type Description
str str

The generated key

CachePut dataclass

Data class used to contain the parameters for a cache_put operation.

See also

slycache.cache_put

CacheRemove dataclass

Data class used to contain the parameters for a cache_remove operation.

See also

slycache.cache_remove

CacheResult dataclass

Data class used to contain the parameters for a cache_result operation.

See also

slycache.cache_result

Slycache

Singleton cache controller class. You should never have to instantiate this class directly. Interact with this class via the slycache instance:

import slycache

slycache.cache_result("{key}")(my_function)

register_backend staticmethod

register_backend(
    name: str,
    backend: CacheInterface,
    default_timeout: Optional[int] = None,
    default_namespace: Optional[
        Union[str, NotSet]
    ] = NOTSET,
)

Register a cache backend.

Parameters:

Name Type Description Default
name str

(str): the name of the cache

required
backend CacheInterface

(:obj:slycache.interface.CacheInterface): An instance of the backend class. This must conform to the interface defined by :class:slycache.interface.CacheInterface

required
default_timeout Optional[int]

(int, optional): the default timeout for this backend (seconds). Defaults to no timeout.

None
default_namespace Optional[Union[str, NotSet]]

(str, optional): the default namespace for this backend. Defaults to None. See :ref:namespaces

NOTSET

with_defaults

with_defaults(**defaults)

Return a new Slycache object with updated defaults.

Parameters:

Name Type Description Default
cache_name

(str, optional): name of the cache to use

required
key_generator

(KeyGenerator, optional): :class:slycache.KeyGenerator object to use for generating and validating keys.

required
timeout

(int, optional): default timeout to use for keys

required
namespace

(str, optional): key namespace to use

required

cache_result

cache_result(
    keys: KeysType,
    *,
    cache_name: Optional[str] = None,
    timeout: Union[int, NotSet] = NOTSET,
    namespace: Union[str, NotSet] = NOTSET,
    skip_get: bool = False,
)

This is a function level decorator function used to mark methods whose returned value is cached, using a key generated from the method parameters, and returned from the cache on later calls with the same parameters.

When a method decorated with cache_result is invoked a cache key will be generated and used to fetch the value from the cache before the decorated method executes. If a value is found in the cache it is returned and the decorated method is never executed. If no value is found the decorated method is invoked and the returned value is stored in the cache with the generated key.

None return values are not cached

The cache operation takes place after the invocation of the decorated function. Any exceptions raised will prevent operation from being executed;

To always invoke the annotated method and still cache the result set skip_get to True. This will disable the pre-invocation cache check.

Example of caching the User object with a key generated from the str and bool parameters.

@slycache.cache_result("{username}_{is_active}")
def get_user(username: str, is_active: bool) -> User:
    ...

Parameters:

Name Type Description Default
keys str or List[str]

key template or list of key templates. These are converted to actual cache keys using the currently active key generator. See :ref:key-generator

required
cache_name str

If set this overrides the currently configured cache for this specific operation.

None
timeout int

If set this overrides the currently configured timeout for this specific operation.

NOTSET
namespace str

If set this overrides the currently configured namespace for this specific operation.

NOTSET
skip_get bool

If set to true the pre-invocation is skipped and the decorated method is always executed with the returned value being cached as normal. This is useful for create or update methods which should always be executed and have their returned value placed in the cache.

Defaults to False.

False

cache_put

cache_put(
    keys: KeysType,
    *,
    cache_value: Optional[str] = None,
    cache_name: Optional[str] = None,
    timeout: Union[int, NotSet] = NOTSET,
    namespace: Union[str, NotSet] = NOTSET,
)

This is a function level decorator used to mark function where one of the function arguments should be stored in the cache. One parameter must be selected using the cache_value argument.

If the function only has a single argument (excluding self) then the cache_value argument may be omitted.

When a function decorated with cache_put is invoked a cache key will be generated and used to store the value selected from the function arguments.

None values are not cached

The cache operation takes place after the invocation of the decorated function. Any exceptions raised will will prevent operation from being executed;

Example of caching the User object:

@slycache.cache_put("{user.username}")
def save_user(user: User):
    ...

Parameters:

Name Type Description Default
keys str or List[str]

key template or list of key templates. These are converted to actual cache keys using the currently active key generator. See :ref:key-generator

required
cache_value str

The name of the function argument to cache. This may only be omitted if the function only has a single argument (excluding self).

None
cache_name str

If set this overrides the currently configured cache for this specific operation.

None
timeout int

If set this overrides the currently configured timeout for this specific operation.

NOTSET
namespace str

If set this overrides the currently configured namespace for this specific operation.

NOTSET

cache_remove

cache_remove(
    keys: KeysType,
    *,
    cache_name: Optional[str] = None,
    namespace: Union[str, NotSet] = NOTSET,
)

This is a function level decorator used to mark function where the invocation results in an entry (or entries) being removed from the specified cache.

When a function decorated with cache_remove is invoked a cache key will be generated by the :ref:key-generator CacheInterface.delete will be invoked on the specified cache.

The cache operation takes place after the invocation of the decorated function. Any exceptions raised will will prevent operation from being executed;

Example of removing the User object from the cache:

@slycache.cache_remove(["{user.username}", "{user.id}"])
def delete_user(user: User):
    ...

Parameters:

Name Type Description Default
keys str or List[str]

key template or list of key templates. These are converted to actual cache keys using the currently active key generator. See :ref:key-generator

required
cache_name str

If set this overrides the currently configured cache for this specific operation.

None
namespace str

If set this overrides the currently configured namespace for this specific operation.

NOTSET

caching

caching(
    *operations: Union[CacheResult, CachePut, CacheRemove],
)

A function level decorator used to execute multiple cache operations after the execution of the decorated function.

When a function decorated with caching is invoked each of the supplied cache operations will be executed in order.

The cache operations are executed after the invocation of the decorated function. Any exceptions raised will prevent all the operations from being executed;

Example of caching the User object in multiple caches:

@slycache.caching(
    CacheResult("{username}", cache_name="local_memory"),
    CacheResult("{username}", cache_name="redis"),
)
def get_user(username: str):
    ...