Cache Module¶
forge.cache — Decorator-based caching with in-memory LRU and Redis backends.
Overview¶
The Cache module provides a simple, decorator-based caching API with pluggable backends. Cache function results with a single decorator, and switch between in-memory and Redis backends by changing configuration.
Installation¶
Quick Start¶
from forge.cache import cached
@cached(ttl=300) # Cache for 5 minutes
async def get_user(user_id: int):
return await db.fetch_user(user_id)
Key Features¶
Configurable TTL¶
Custom Cache Keys¶
Backend Selection¶
Invalidation¶
Manual Cache Operations¶
from forge.cache import CacheModule
cache = CacheModule()
await cache.set("key", value, ttl=300)
value = await cache.get("key")
exists = await cache.has("key")
await cache.delete("key")
await cache.clear()
API Reference¶
Classes¶
CacheBackendError ¶
Raised when a cache backend operation fails or is unavailable.
CacheError ¶
Base exception for all cache-related errors.
CacheModule ¶
Functions:¶
cached ¶
cached(ttl: int | None = None, key: str | None = None, namespace: str | None = None, backend: CacheBackend | None = None) -> Callable[[F], F]
Decorator for caching async function results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl
|
int | None
|
Time-to-live in seconds. Defaults to cache module default_ttl. |
None
|
key
|
str | None
|
Cache key template. Supports {arg_name} interpolation from function args. |
None
|
namespace
|
str | None
|
Optional namespace prefix for the cache key. |
None
|
backend
|
CacheBackend | None
|
Optional custom backend to use instead of the active module. |
None
|
invalidate
async
¶
Convenience helper to invalidate a cache key in the active cache module.