An HTTP response cache with size budgets, ratio-based truncation, TTL expiry, and detailed statistics.
- Size Budgets - Limit cached response sizes (
"100kb","1mb",1024) - Ratio Limits -
"ratio:0.5"to cache only 50% of response body - TTL Expiry - Automatic expiration with configurable time-to-live
- Per-Request Overrides - Override default limits for individual entries
- Statistics - Track hits, misses, truncations, evictions
- Entry Metadata -
cache_size,cache_truncated,cache_ratioon every entry
from cachelimit import ResponseCache
# Create cache with 100KB default limit
cache = ResponseCache(max_response_size="100kb", default_ttl=3600)
# Cache a response
entry = cache.put("https://api.example.com/data", response_body)
print(entry.cache_truncated) # True if body exceeded limit
# Retrieve
entry = cache.get("https://api.example.com/data")
if entry:
print(f"Cached {entry.cache_size} bytes")
# Ratio-based limiting
cache = ResponseCache(max_response_size="ratio:0.5")
entry = cache.put("https://example.com", b"1234567890")
# entry.body == b"12345" (50% of original)
# Per-request override
entry = cache.put("https://example.com", body, max_response_size="1mb")| Format | Example | Description |
|---|---|---|
| Integer | 1024 |
Absolute byte limit |
| String bytes | "512kb", "1mb" |
Human-readable sizes |
| Ratio colon | "ratio:0.5" |
Keep 50% of body |
| Ratio equals | "ratio=0.5" |
Same as above |
| Ratio suffix | "0.5 ratio" |
Same as above |
pytest