Skip to content

Reference

starlette_caches.middleware

CacheControlMiddleware

CacheControlMiddleware(
    app: ASGIApp, **kwargs: Unpack[CacheDirectives]
)

Middleware which handles Cache-Control headers for upstream cache proxies.

Other Parameters:

Name Type Description
max_age float

The maximum age of the response in seconds.

public bool

Not implemented

private bool

Not implemented

**kwargs Unpack[CacheDirectives]

Additional Cache-Control directives

See Also
Source code in src/starlette_caches/middleware.py
193
194
195
def __init__(self, app: ASGIApp, **kwargs: typing.Unpack[CacheDirectives]) -> None:
    self.app = app
    self.kwargs = kwargs

CacheMiddleware

CacheMiddleware(
    app: ASGIApp,
    *,
    cache: BaseCache,
    rules: Sequence[Rule] | None = None,
)

Middleware that caches responses.

This middleware caches responses based on the request path. It can be configured with rules that determine which requests and responses should be cached. Configure the rules by passing a sequence of Rule instances to the rules argument. See Rules for more information on how to configure rules.

Parameters:

Name Type Description Default
app ASGIApp

The ASGI application to wrap.

required
cache BaseCache

The cache instance to use.

required
rules Sequence[Rule] | None

A sequence of rules for caching behavior.

None
Source code in src/starlette_caches/middleware.py
51
52
53
54
55
56
57
58
59
60
61
62
63
def __init__(
    self,
    app: ASGIApp,
    *,
    cache: Cache,
    rules: Sequence[Rule] | None = None,
) -> None:
    if rules is None:
        rules = [Rule()]

    self.app = app
    self.cache = cache
    self.rules = rules

starlette_caches.rules

Rule dataclass

Rule(
    match: str | Pattern | Iterable[str | Pattern] = "*",
    status: int | Iterable[int] | None = None,
    ttl: float | None = None,
)

A rule for configuring caching behavior.

A rule is matched if the request path matches the match attribute and the response status code matches the status attribute.

If the rule matches, the response will be cached for the duration specified by the ttl attribute. A value of 0 will disable caching for the response.

All arguments are optional.

match class-attribute instance-attribute

match: str | Pattern | Iterable[str | Pattern] = '*'

The request path to match.

If a regular expression is provided, it will be matched against the request path.

If a sequence is provided, the request path will be matched against each item in the sequence.

If the request path matches any item in the sequence, the rule will match.

status class-attribute instance-attribute

status: int | Iterable[int] | None = None

An integer or sequence of integers that match the response status code.

If the response status code matches any item in the sequence, the rule will match.

ttl class-attribute instance-attribute

ttl: float | None = None

Time-to-live for the cached response in seconds.

If set, the response will be cached for the specified duration. If not set, the default TTL will be used. A value of 0 will disable caching for the response.

starlette_caches.helpers

CacheHelper

CacheHelper(request: Request)

Bases: _BaseCacheMiddlewareHelper

Helper class for the CacheMiddleware.

This helper class provides a way to maniuplate the cache middleware.

If using FastAPI, you can use the CacheHelper as a dependency in your endpoint.

Example
async def invalidate_cache(helper: Annotated[CacheHelper, Depends()]) -> None:
    await helper.invalidate_cache_for("my_route")
Source code in src/starlette_caches/helpers.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def __init__(self, request: Request) -> None:
    """Initialize the helper with the request and the cache middleware instance.

    Args:
        request: The request object.

    Raises:
        MissingCaching: If the cache middleware instance is not found in the scope
                        or if the cache middleware instance is not an instance of
                        `CacheMiddleware`.

    """
    self.request = request

    if SCOPE_NAME not in request.scope:  # pragma: no cover
        raise MissingCaching(
            "No CacheMiddleware instance found in the ASGI scope. Did you forget "
            "to wrap the ASGI application with `CacheMiddleware`?"
        )

    middleware = request.scope[SCOPE_NAME]
    if not isinstance(middleware, CacheMiddleware):  # pragma: no cover
        raise MissingCaching(
            f"A scope variable named {SCOPE_NAME!r} was found, but it does not "
            "contain a `CacheMiddleware` instance. It is likely that an "
            "incompatible middleware was added to the middleware stack."
        )

    self.middleware = middleware

invalidate_cache_for async

invalidate_cache_for(
    url: Union[str, URL],
    *,
    headers: Union[Mapping[str, str], None] = None,
) -> None

Invalidate the cache for a given named route or full url.

headers will be used to generate the cache key. The Vary header from the cached response will determine which headers will be used.

Parameters:

Name Type Description Default
url Union[str, URL]

The URL to invalidate or name of a starlette route.

required
headers Union[Mapping[str, str], None]

The headers used to generate the cache key.

None
Source code in src/starlette_caches/helpers.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
async def invalidate_cache_for(
    self,
    url: typing.Union[str, URL],
    *,
    headers: typing.Union[Mapping[str, str], None] = None,
) -> None:
    """Invalidate the cache for a given named route or full url.

    `headers` will be used to generate the cache key. The `Vary` header from the
    cached response will determine which headers will be used.

    Args:
        url: The URL to invalidate or name of a starlette route.
        headers: The headers used to generate the cache key.

    """
    if not isinstance(url, URL):
        url = self.request.url_for(url)

    if not isinstance(headers, Headers):
        headers = Headers(headers)

    await delete_from_cache(url, vary=headers, cache=self.middleware.cache)

starlette_caches.decorators

cache_control module-attribute

cache_control = _middleware_to_decorator(
    CacheControlMiddleware
)

Wrap an ASGI endpoint with starlette_caches.middleware.CacheControlMiddleware.

This decorator provides the same behavior as CacheControlMiddleware, but at an endpoint level.

Raises 'ValueError' if the wrapped callable isn't an ASGI application.

cached module-attribute

cached = _middleware_to_decorator(CacheMiddleware)

Wrap an ASGI endpoint with starlette_caches.middleware.CacheMiddleware.

This decorator provides the same behavior as CacheMiddleware, but at an endpoint level.

Raises 'ValueError' if the wrapped callable isn't an ASGI application.

starlette_caches.exceptions

DuplicateCaching

Bases: StarletteCachesException

Raised when multiple cache middleware were detected.

MissingCaching

Bases: StarletteCachesException

Raised when no cache middleware was detected.

RequestNotCachable

RequestNotCachable(request: Request)

Bases: StarletteCachesException

Raised internally when a request cannot be cached.

Source code in src/starlette_caches/exceptions.py
12
13
14
def __init__(self, request: Request) -> None:
    super().__init__()
    self.request = request

ResponseNotCachable

ResponseNotCachable(response: Response)

Bases: StarletteCachesException

Raised internally when a response cannot be cached.

Source code in src/starlette_caches/exceptions.py
20
21
22
def __init__(self, response: Response) -> None:
    super().__init__()
    self.response = response