HTTPX Cache Persistent Offline Replay
Add a persistent caching layer to httpx with httpx-cache, replaying stale responses offline and refreshing in the background.
Code
import asyncio
import httpx
from httpx_cache import CacheControlTransport
client = httpx.AsyncClient(
transport=CacheControlTransport(
cache=httpx_cache.FileCache(cache_dir='.http_cache'),
cacheable_methods=('GET',),
cacheable_status_codes=(200, 301, 404),
)
)
async def fetch_product(product_id: int) -> dict | None:
try:
resp = await client.get(f'https://api.example.com/products/{product_id}')
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError:
return None
async def warm_cache(ids: list[int]) -> int:
results = await asyncio.gather(
*(fetch_product(pid) for pid in ids),
return_exceptions=True,
)
return sum(1 for r in results if not isinstance(r, Exception))
async def main() -> None:
await warm_cache(list(range(10)))
# 断网场景:文件缓存仍可回放此前成功的响应
product = await fetch_product(3)
print('served from cache offline:', product is not None)
await client.aclose()
asyncio.run(main())Inside the snippet
The code’s whole job belongs to the functions fetch_product, warm_cache and main.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. Everything borrowed from httpx_cache is visible in one line: CacheControlTransport.
Points of care
- Plan for an install step:
httpx_cache,asyncioandhttpxare a real dependency, resolved by the package manager.
Putting it to use
The main signature reads def fetch_product(product_id: int) -> dict | None
The demo output is labeled (served from cache offline:), so every printed line maps back to its originating operation.
Callers only need fetch_product — everything else stays internal.
Core lines
async def fetch_product(product_id: int) -> dict | None:
try:
resp = await client.get(f'https://api.example.com/products/{product_id}')
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError:
return None
async def main() -> None:
await warm_cache(list(range(10)))
# 断网场景:文件缓存仍可回放此前成功的响应
product = await fetch_product(3)
print('served from cache offline:', product is not None)
await client.aclose()
async def warm_cache(ids: list[int]) -> int:
results = await asyncio.gather(
*(fetch_product(pid) for pid in ids),
return_exceptions=True,
)
return sum(1 for r in results if not isinstance(r, Exception))
Interactive Tools for This Topic
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `httpx_cache`, `asyncio` and `httpx`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.