Add a cache status header to the response

The header name is configurable, and defaults to `X-FastAPI-Cache`,
the value is either `HIT` or `MISS`.

Note that the header is not set at all when the cache is disabled.
This commit is contained in:
Martijn Pieters
2023-05-12 14:12:00 +01:00
committed by Martijn Pieters
parent 29426de95f
commit 915f3dd8f2
4 changed files with 28 additions and 3 deletions

View File

@@ -144,6 +144,7 @@ def cache(
expire = expire or FastAPICache.get_expire()
key_builder = key_builder or FastAPICache.get_key_builder()
backend = FastAPICache.get_backend()
cache_status_header = FastAPICache.get_cache_status_header()
cache_key = key_builder(
func,
@@ -181,6 +182,7 @@ def cache(
{
"Cache-Control": f"max-age={expire}",
"ETag": f"W/{hash(to_cache)}",
cache_status_header: "MISS",
}
)
@@ -191,6 +193,7 @@ def cache(
{
"Cache-Control": f"max-age={ttl}",
"ETag": etag,
cache_status_header: "HIT",
}
)