mirror of
https://github.com/long2ice/fastapi-cache.git
synced 2026-03-24 20:47:54 +00:00
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:
committed by
Martijn Pieters
parent
29426de95f
commit
915f3dd8f2
@@ -22,6 +22,7 @@ class FastAPICache:
|
||||
_init: ClassVar[bool] = False
|
||||
_coder: ClassVar[Optional[Type[Coder]]] = None
|
||||
_key_builder: ClassVar[Optional[KeyBuilder]] = None
|
||||
_cache_status_header: ClassVar[Optional[str]] = None
|
||||
_enable: ClassVar[bool] = True
|
||||
|
||||
@classmethod
|
||||
@@ -32,6 +33,7 @@ class FastAPICache:
|
||||
expire: Optional[int] = None,
|
||||
coder: Type[Coder] = JsonCoder,
|
||||
key_builder: KeyBuilder = default_key_builder,
|
||||
cache_status_header: str = "X-FastAPI-Cache",
|
||||
enable: bool = True,
|
||||
) -> None:
|
||||
if cls._init:
|
||||
@@ -42,6 +44,7 @@ class FastAPICache:
|
||||
cls._expire = expire
|
||||
cls._coder = coder
|
||||
cls._key_builder = key_builder
|
||||
cls._cache_status_header = cache_status_header
|
||||
cls._enable = enable
|
||||
|
||||
@classmethod
|
||||
@@ -52,6 +55,7 @@ class FastAPICache:
|
||||
cls._expire = None
|
||||
cls._coder = None
|
||||
cls._key_builder = None
|
||||
cls._cache_status_header = None
|
||||
cls._enable = True
|
||||
|
||||
@classmethod
|
||||
@@ -78,6 +82,11 @@ class FastAPICache:
|
||||
assert cls._key_builder, "You must call init first!" # nosec: B101
|
||||
return cls._key_builder
|
||||
|
||||
@classmethod
|
||||
def get_cache_status_header(cls) -> str:
|
||||
assert cls._cache_status_header, "You must call init first!" # nosec: B101
|
||||
return cls._cache_status_header
|
||||
|
||||
@classmethod
|
||||
def get_enable(cls) -> bool:
|
||||
return cls._enable
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user