From e4a0df62dd2f8988187e72b9911cae7c8dd843a4 Mon Sep 17 00:00:00 2001 From: John Lyu Date: Thu, 9 May 2024 14:32:02 +0800 Subject: [PATCH] fix #424, no-cache should store the result to cache --- fastapi_cache/decorator.py | 6 +++--- tests/test_decorator.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 4c7cf33..40a1920 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -72,7 +72,7 @@ def _uncacheable(request: Optional[Request]) -> bool: Returns true if: - Caching has been disabled globally - This is not a GET request - - The request has a Cache-Control header with a value of "no-store" or "no-cache" + - The request has a Cache-Control header with a value of "no-store" """ if not FastAPICache.get_enable(): @@ -81,7 +81,7 @@ def _uncacheable(request: Optional[Request]) -> bool: return False if request.method != "GET": return True - return request.headers.get("Cache-Control") in ("no-store", "no-cache") + return request.headers.get("Cache-Control") == "no-store" def cache( @@ -182,7 +182,7 @@ def cache( ) ttl, cached = 0, None - if cached is None: # cache miss + if cached is None or (request is not None and request.headers.get("Cache-Control") == "no-cache") : # cache miss result = await ensure_async_func(*args, **kwargs) to_cache = coder.encode(result) diff --git a/tests/test_decorator.py b/tests/test_decorator.py index fefa182..f8d2028 100644 --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -112,3 +112,28 @@ def test_alternate_injected_namespace() -> None: response = client.get("/namespaced_injection") assert response.headers.get("X-FastAPI-Cache") == "MISS" assert response.json() == {"__fastapi_cache_request": 42, "__fastapi_cache_response": 17} + +def test_cache_control() -> None: + with TestClient(app) as client: + response = client.get("/uncached_put") + assert "X-FastAPI-Cache" not in response.headers + assert response.json() == {"value": 1} + + # HIT + response = client.get("/uncached_put") + assert response.headers.get("X-FastAPI-Cache") == "HIT" + assert response.json() == {"value": 1} + + # no-cache + response = client.get("/uncached_put", headers={"Cache-Control": "no-cache"}) + assert response.json() == {"value": 2} + + response = client.get("/uncached_put") + assert response.json() == {"value": 2} + + # no-store + response = client.get("/uncached_put", headers={"Cache-Control": "no-store"}) + assert response.json() == {"value": 3} + + response = client.get("/uncached_put") + assert response.json() == {"value": 2}