cache_result¶
The decorator that wraps a function in a CachedWrapper. See the
cache_result guide for an
overview and worked examples.
cache_result ¶
cache_result(
key_constructor: KeyConstructor
| dict[str, Any]
| type[KeyConstructor] = DefaultKeyConstructor,
ttl: int | None = 3600,
invalidates_on: list[InvalidationRule] | None = None,
cache_if: Callable | None = None,
cache_unless: Callable | None = None,
)
Cache a function's return value, with optional invalidation triggered by Django model signals.
Works for sync and async targets. Returns a decorator that replaces the target function with a CachedWrapper.
Example
::
@cache_result(
key_constructor=UserKeyConstructor,
ttl=300,
invalidates_on=[
InvalidationRule(
model=User,
field_mapping={"user_id": "id"},
rewarm=True,
)
],
)
def get_user_data(user_id: int) -> dict:
return expensive_computation(user_id)
CachedWrapper ¶
CachedWrapper(
func: Callable[P, T],
key_constructor: KeyConstructor
| dict[str, Any]
| type[KeyConstructor],
ttl: int | None,
invalidates_on: list[InvalidationRule],
cache_if: Callable | None = None,
cache_unless: Callable | None = None,
)
Bases: Generic[P, T]
Callable wrapper that caches a function's return value in the Django cache.
Produced by applying cache_result to a function. Calling the wrapper behaves like calling the original function, with results looked up in and stored in the Django cache. When the wrapped function is async, every cache I/O runs through Django's async cache API and the call returns a coroutine.
get_with_metadata ¶
Run the call and return (value, metadata) so callers can read cache status and timestamps.
get_cache_only ¶
Return the cached value without running the function. Returns CACHE_MISSING on miss.
get_cache_key ¶
Return the cache key the wrapper would use for these call arguments.
get_cached_metadata ¶
Return the metadata dict for the cached call, or None if there is no cache entry yet.
refresh ¶
Run the function again and overwrite the cache entry for these call arguments.
bypass_cache ¶
Call the wrapped function directly, skipping both cache reads and cache writes.
delete_cache ¶
Drop the cache entry for these specific call arguments.
delete_by_prefix ¶
Wipe every cache entry that shares the partition prefix derived from these call arguments.
invalidate_all ¶
Drop every cache entry this wrapper has ever written, across every set of call arguments.
set_response_cache_header ¶
Attach cache metadata as X-Cached-at, X-Cache-reset-at, and X-Cache-status headers on a DRF response.
CacheStatus ¶
Bases: str, Enum
How a cached call resolved.
Carried in the response metadata so callers and monitoring can tell hits from misses.