Skip to main content

hawkapi-cache

Response caching for HawkAPI — decorator + middleware + Redis/memory backends + tag-based invalidation.

Install

pip install hawkapi-cache              # memory backend
pip install hawkapi-cache[redis]       # + Redis backend

Quickstart

from hawkapi import HawkAPI, Request
from hawkapi_cache import init_cache, cache, RedisCacheBackend

app = HawkAPI()
init_cache(app, backend=RedisCacheBackend.from_url("redis://localhost:6379/0"))

@app.get("/users/{user_id:int}")
@cache(ttl=60, tags=["users", "user:{user_id}"])
async def get_user(request: Request, user_id: int):
    return await db.fetch_user(user_id)

@app.post("/users/{user_id:int}/refresh")
async def refresh(request: Request, user_id: int):
    await app.state.cache.invalidate_tags([f"user:{user_id}"])
    return {"ok": True}

In-memory is the default (no Redis required):

from hawkapi_cache import init_cache
init_cache(app)   # MemoryCacheBackend(max_size=10_000)

@cache(...) reference

Arg Default Notes
ttl 60 Seconds.
tags () Group invalidation. {name} placeholders pulled from path params.
vary () Request headers that change the response. Values appended to the cache key.
key_func None (Request) -> str override. Replaces the default key entirely.
condition None (Request) -> bool — return False to bypass cache.

Only GET / HEAD requests with 2xx responses are cached. Other methods and non-2xx responses pass through.

Every cached response gets an X-Cache: HIT or X-Cache: MISS header.

Recipes

Per-user cache via vary

@cache(ttl=60, vary=("authorization",))
async def me(request: Request):
    ...

Bypass cache for authenticated users

@cache(ttl=60, condition=lambda r: not r.headers.get("authorization"))
async def feed(request: Request):
    ...

Tag-driven invalidation

@cache(ttl=300, tags=["posts", "post:{post_id}"])
async def get_post(request: Request, post_id: int): ...

@app.put("/posts/{post_id:int}")
async def update(request: Request, post_id: int):
    ...
    await app.state.cache.invalidate_tags([f"post:{post_id}"])

Custom key

@cache(ttl=60, key_func=lambda r: f"my:{r.url.path}:{r.headers.get('x-tenant')}")
async def list_orders(request: Request): ...

Backends

MemoryCacheBackend(max_size=10_000)

LRU + per-key TTL, single-process. Use for tests and small deployments.

RedisCacheBackend.from_url("redis://host/0", prefix="hawkapi-cache:")

Multi-process safe. Tag index uses Redis SETs; invalidate_tags is a pipelined SUNION + DEL. Add hawkapi-cache[redis] extra.

Development

git clone https://github.com/Hawk-API/hawkapi-cache.git
cd hawkapi-cache
uv sync --extra dev
uv run pytest -q
uv run ruff check . && uv run ruff format --check .
uv run pyright src/

License

MIT.

Metadata

Release files for hawkapi-cache 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hawkapi-cache 0.2.1
File Size Uploaded
hawkapi_cache-0.2.1.tar.gz 30.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for hawkapi-cache 0.2.1
File Interpreter ABI Platform
hawkapi_cache-0.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 44.7 kB

Release files / hawkapi_cache-0.2.1.tar.gz

Download URL hawkapi_cache-0.2.1.tar.gz
Size 30.6 kB
Tags Source
SHA-256 checksum
How to use checksums
669842608af6cee40ae9bdc7f3f1d291ca3c907ebb7c57820a02ed0dac9b147f
BLAKE2b-256 checksum
How to use checksums
ca737203eabf0e6f6d7396e5bc5babbb2cd79c3960140dc4ece3a3480038bf83
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 10, 2026.

Transparency log

Release files / hawkapi_cache-0.2.1-py3-none-any.whl

Download URL hawkapi_cache-0.2.1-py3-none-any.whl
Size 14.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5351005d807d04c0a04522da0baf7dda08f43fff1695342779241fc6d0687a64
BLAKE2b-256 checksum
How to use checksums
9c01ff76b89eb0937340dae7b951a14a16678a84eac505f108497df0dcde328b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 10, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page