Skip to content

Key Constructors

Declarative cache-key builders. See the Key Constructors guide for an overview and worked examples.

KeyConstructor

Declarative cache-key generator.

Subclass and declare CacheKeyField attributes to build a stable cache key for a function.

Example

::

class UserKey(KeyConstructor):
    user = ArgsKeyField("user_id", partition=True)
    version = ConstantKeyField("v", "1")

    class Meta:
        namespace = "myapp"
        version = 1

get_version

get_version() -> int

Return the version declared on Meta, bumping it invalidates all keys for this constructor.

get_fields

get_fields()

Return a fresh dict of the declared CacheKeyField attributes.

build_partition

build_partition(func, args, kwargs)

Build the partition portion of the cache key from fields declared with partition=True.

build_key_prefix

build_key_prefix(func: Callable[P, T], args, kwargs)

Build the cache key prefix from namespace, function identifier, and partition.

build_key_suffix

build_key_suffix(func, args, kwargs)

Build the cache key suffix from non-partition fields, hashing it on overflow when configured.

generate_key

generate_key(func: Callable[P, T], args, kwargs) -> str

Build and return the full cache key for the given call.

get_function_identifier staticmethod

get_function_identifier(func: Callable[P, T])

Return the function's full dotted path, including class name for bound methods.

InlineKeyConstructor

Factory that builds a KeyConstructor subclass from a plain dict of fields.

Useful for a one-off constructor on a single cache_result call without writing out a full subclass.

Example

::

UserKey = InlineKeyConstructor(
    fields={"user": ArgsKeyField("user_id", partition=True)},
    namespace="myapp",
)

@cache_result(UserKey, ttl=60)
def get_user(user_id: int): ...

DefaultKeyConstructor

Bases: KeyConstructor

Built-in key constructor that captures every positional and keyword argument.

Used by cache_result when no key_constructor is supplied.