Skip to content

Commit af6301f

Browse files
author
John Lyu
committed
Merge branch 'fix-no-cache' into fix
2 parents 19c4d02 + e4a0df6 commit af6301f

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

fastapi_cache/decorator.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def _uncacheable(request: Optional[Request]) -> bool:
7272
Returns true if:
7373
- Caching has been disabled globally
7474
- This is not a GET request
75-
- The request has a Cache-Control header with a value of "no-store" or "no-cache"
75+
- The request has a Cache-Control header with a value of "no-store"
7676
7777
"""
7878
if not FastAPICache.get_enable():
@@ -81,7 +81,7 @@ def _uncacheable(request: Optional[Request]) -> bool:
8181
return False
8282
if request.method != "GET":
8383
return True
84-
return request.headers.get("Cache-Control") in ("no-store", "no-cache")
84+
return request.headers.get("Cache-Control") == "no-store"
8585

8686

8787
def cache(
@@ -182,7 +182,7 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R:
182182
)
183183
ttl, cached = 0, None
184184

185-
if cached is None: # cache miss
185+
if cached is None or (request is not None and request.headers.get("Cache-Control") == "no-cache") : # cache miss
186186
result = await ensure_async_func(*args, **kwargs)
187187
to_cache = coder.encode(result)
188188

tests/test_decorator.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,28 @@ def test_alternate_injected_namespace() -> None:
112112
response = client.get("/namespaced_injection")
113113
assert response.headers.get("X-FastAPI-Cache") == "MISS"
114114
assert response.json() == {"__fastapi_cache_request": 42, "__fastapi_cache_response": 17}
115+
116+
def test_cache_control() -> None:
117+
with TestClient(app) as client:
118+
response = client.get("/uncached_put")
119+
assert "X-FastAPI-Cache" not in response.headers
120+
assert response.json() == {"value": 1}
121+
122+
# HIT
123+
response = client.get("/uncached_put")
124+
assert response.headers.get("X-FastAPI-Cache") == "HIT"
125+
assert response.json() == {"value": 1}
126+
127+
# no-cache
128+
response = client.get("/uncached_put", headers={"Cache-Control": "no-cache"})
129+
assert response.json() == {"value": 2}
130+
131+
response = client.get("/uncached_put")
132+
assert response.json() == {"value": 2}
133+
134+
# no-store
135+
response = client.get("/uncached_put", headers={"Cache-Control": "no-store"})
136+
assert response.json() == {"value": 3}
137+
138+
response = client.get("/uncached_put")
139+
assert response.json() == {"value": 2}

0 commit comments

Comments
 (0)