Skip to content

API Reference

Core

CacheConfig

sqlmodel_cache.CacheConfig dataclass

Per-model cache configuration.

Assign as a class variable on any SQLModel subclass::

class Hero(SQLModel, table=True):
    __cache_config__ = CacheConfig(ttl=300)
    id: int | None = Field(default=None, primary_key=True)
    name: str

Attributes:

Name Type Description
enabled bool

When False, caching is disabled for this model even if the library is configured. Defaults to True.

ttl int | None

Time-to-live in seconds for cached entries. None means fall back to the global default_ttl set in SQLModelCache.configure().

SQLModelCache

sqlmodel_cache.SQLModelCache

Application-level interface for configuring sqlmodel-cache.

Call configure() once at startup before any SQLModel session operations on cache-enabled models.

configure(transport, *, default_ttl=300, key_prefix='sqlmodelcache', enabled=True) classmethod

Configure the library with a transport and global defaults.

Parameters:

Name Type Description Default
transport CacheTransport | AsyncCacheTransport

A CacheTransport implementation (e.g. RedisSyncTransport). FakeTransport from tests/unit/fakes.py is suitable for tests.

required
default_ttl int

Default TTL in seconds for cached entries when the model's CacheConfig.ttl is None. Defaults to 300.

300
key_prefix str

Redis key prefix. Defaults to "sqlmodelcache". Override per-deployment to avoid collisions across apps.

'sqlmodelcache'
enabled bool

When False, the library is fully disabled — no cache reads, writes, or invalidations occur. All session.get() calls fall through to the database. Defaults to True.

True

get_config() classmethod

Return active configuration; raises ConfigurationError if unconfigured.

reset() classmethod

Clear configuration and remove event listeners.

Intended exclusively for test isolation — call in pytest fixture teardown to prevent state leaking between tests::

@pytest.fixture(autouse=True)
def reset_cache():
    yield
    SQLModelCache.reset()

Errors

CacheError

sqlmodel_cache.CacheError

Bases: Exception

Base exception for all sqlmodel-cache errors.

Catch this to handle any error raised by the library::

try:
    session.get(Hero, 1)
except CacheError:
    ...  # library-level error (not Redis errors — those are suppressed)

ConfigurationError

sqlmodel_cache.ConfigurationError

Bases: CacheError

Raised when a cache operation is attempted before configuration.

This is raised by _state.get_config() when SQLModelCache.configure() has not yet been called at application startup::

# triggers ConfigurationError:
session.get(Hero, 1)  # before SQLModelCache.configure(...)

Resolution: call SQLModelCache.configure(transport=..., default_ttl=...) once at application startup before any SQLModel session operations.


Transports

RedisSyncTransport

sqlmodel_cache.transport.RedisSyncTransport

Synchronous Redis transport wrapping redis.Redis.

Satisfies :class:~sqlmodel_cache.transport._protocols.CacheTransport structurally — no inheritance required.

Parameters:

Name Type Description Default
client Redis

A configured redis.Redis instance.

required

delete(*keys)

Remove one or more keys from the cache.

get(key)

Return cached bytes or None if the key does not exist.

set(key, value, ttl)

Store value under key with an expiry of ttl seconds.

RedisAsyncTransport

sqlmodel_cache.transport.RedisAsyncTransport

Asynchronous Redis transport wrapping redis.asyncio.Redis.

Satisfies :class:~sqlmodel_cache.transport._protocols.AsyncCacheTransport structurally — no inheritance required.

Parameters:

Name Type Description Default
client Redis

A configured redis.asyncio.Redis instance.

required
Note

redis.asyncio is NOT imported at module level — this ensures no event loop is required at import time (NFR-COMPAT-5).

delete(*keys) async

Remove one or more keys from the cache.

get(key) async

Return cached bytes or None if the key does not exist.

set(key, value, ttl) async

Store value under key with an expiry of ttl seconds.


Per-Request Control (execution_options)

Pass these keys to execution_options on any session.get() call to control caching on a per-call basis without changing the model's CacheConfig.

Key Type Description
cache bool Set to False to bypass the cache for this call entirely
cache_ttl int Override TTL (seconds) for this specific call

Example — Bypass cache for a single call:

with Session(engine) as session:
    # Always queries the database, never reads or writes the cache
    hero = session.get(Hero, 1, execution_options={"cache": False})

Example — Custom TTL for a single call:

with Session(engine) as session:
    # Cache this result for 60 seconds, ignoring the model's __cache_config__.ttl
    hero = session.get(Hero, 1, execution_options={"cache_ttl": 60})

CacheConfig Field Reference

Field Type Default Description
enabled bool True When False, all session.get() calls for this model skip the cache
ttl int \| None None TTL in seconds; None falls back to SQLModelCache.configure(default_ttl=...)

SQLModelCache.configure() Parameter Reference

Parameter Type Default Description
transport CacheTransport \| AsyncCacheTransport required Redis transport instance
default_ttl int 300 Default TTL (seconds) for models without an explicit CacheConfig.ttl
key_prefix str "sqlmodelcache" Redis key prefix; override per-deployment to avoid key collisions
enabled bool True Global kill switch; False disables all caching, reads, and invalidations

Raised when cache operations are attempted before SQLModelCache.configure() is called.

sqlmodel_cache.transport

RedisSyncTransport

Synchronous Redis transport wrapping redis.Redis.

RedisAsyncTransport

Asynchronous Redis transport wrapping redis.asyncio.Redis.