Caching¶
- class alchemiq.CacheBackend(*args, **kwargs)[source]¶
Bases:
ProtocolStructural protocol for cache backends.
Implemented by
InMemoryCache(core, no extra) andRedisCache(requires the[redis]extra, built automatically byconfigure_cache()when a Redisurlis supplied).Any object that exposes
default_ttl,namespace, and the five async methods below satisfies this protocol (isinstancecheck via@runtime_checkable).See also
configure_cache()- register a backend process-globally.- async delete(*keys)[source]¶
Delete one or more keys; no-ops on missing keys.
- Parameters:
keys (str)
- Return type:
None
- class alchemiq.InMemoryCache(*, default_ttl=60, namespace='aq')[source]¶
Bases:
objectPure-Python
CacheBackendfor tests and small single-process apps.Backed by a plain
dict; no external dependencies. TTL is enforced lazily onget. Counter keys (used by the version-invalidation scheme) never expire.E.g.:
from alchemiq.cache import InMemoryCache, configure_cache configure_cache(backend=InMemoryCache(default_ttl=120, namespace="myapp"))
Note
Not safe for use across multiple processes or workers - use
configure_cache()with a Redisurlfor multi-process deployments.- async delete(*keys)[source]¶
Remove one or more keys; silently ignores missing keys.
- Parameters:
keys (str)
- Return type:
None
- alchemiq.configure_cache(url=None, *, backend=None, default_ttl=60, namespace='aq', **redis_kw)[source]¶
Set the process-global cache backend.
Pass an explicit
backendinstance, or a Redis connectionurl(requires the[redis]extra). Only one may be provided. Callreset_cache()to clear the global backend (useful in tests).E.g.:
from alchemiq.cache import InMemoryCache, configure_cache, reset_cache # in-process cache (no dependencies): configure_cache(backend=InMemoryCache(default_ttl=120)) # Redis (requires [redis] extra): configure_cache(url="redis://localhost:6379/0")
- Parameters:
url (str | None) – Redis connection URL; builds a
CacheBackendbacked byredis.asyncio. Requirespip install 'alchemiq[redis]'.backend (CacheBackend | None) – A
CacheBackendinstance to use directly. When given,default_ttlandnamespaceare ignored.default_ttl (int) – Default TTL in seconds for Redis-built backends (default 60).
namespace (str) – Key prefix for Redis-built backends (default
"aq").redis_kw (Any)
- Raises:
ConfigError – if neither
urlnorbackendis provided.ImportError – if
urlis given but the[redis]extra is not installed.
- Return type:
None
See also
InMemoryCache- zero-dependency backend for tests.