-
-
Notifications
You must be signed in to change notification settings - Fork 181
Add no-store, no-cache in Cache-Control headers #373
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Bharat23
wants to merge
13
commits into
long2ice:main
Choose a base branch
from
Bharat23:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+115
−27
Open
Changes from 4 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
85443b4
Add no-store, no-cache in Cache-Control headers
83ff773
Merge branch 'main' into main
Bharat23 d52bb8a
merge: upstream repo
Bharat23 7986360
update README with Notes on cache control section
Bharat23 4b37ca7
convert list to set comprehension
Bharat23 6e180e7
remove header key case conversion
fe5a9d7
Add changelog
bbd3a2d
chore: update deps
long2ice 6767c01
Merge branch 'main' into main
long2ice 39ff947
Merge branch 'main' into main
long2ice c2020b4
fix lint ignore comment
Bharat23 7cccf80
replace global module ignore to inline
Bharat23 7f13673
fix mypy issue
Bharat23 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,6 +11,7 @@ | |
TypeVar, | ||
Union, | ||
cast, | ||
Set, | ||
) | ||
|
||
if sys.version_info >= (3, 10): | ||
|
@@ -81,7 +82,23 @@ def _uncacheable(request: Optional[Request]) -> bool: | |
return False | ||
if request.method != "GET": | ||
return True | ||
return request.headers.get("Cache-Control") == "no-store" | ||
return False | ||
|
||
def _extract_cache_control_headers(request: Optional[Request]) -> Set[str]: | ||
"""Extracts Cache-Control header | ||
1. Convert all header to lowercase to make it case insensitive | ||
2. Split on comma (,) | ||
3. Strip whitespaces | ||
4. convert to all lower case | ||
|
||
returns an empty set if header not set | ||
""" | ||
if request is not None: | ||
headers = {header_key.lower(): header_val for header_key, header_val in request.headers.items()} | ||
cache_control_header = headers.get("cache-control", None) | ||
if cache_control_header: | ||
return set([cache_control_val.strip().lower() for cache_control_val in cache_control_header.split(",")]) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be set comprehension imo {cache_control_val.strip().lower() for cache_control_val in cache_control_header.split(",")} There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @sultaniman thanks for pointing it out. Pushed the suggested change. |
||
return set() | ||
|
||
|
||
def cache( | ||
|
@@ -161,6 +178,8 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R: | |
key_builder = key_builder or FastAPICache.get_key_builder() | ||
backend = FastAPICache.get_backend() | ||
cache_status_header = FastAPICache.get_cache_status_header() | ||
cache_control_headers = _extract_cache_control_headers(request=request) | ||
response_headers = {"Cache-Control": cache_control_headers.copy()} | ||
|
||
cache_key = key_builder( | ||
func, | ||
|
@@ -174,21 +193,30 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R: | |
cache_key = await cache_key | ||
assert isinstance(cache_key, str) # noqa: S101 # assertion is a type guard | ||
|
||
ttl, cached = 0, None | ||
try: | ||
ttl, cached = await backend.get_with_ttl(cache_key) | ||
# no-cache: Assume cache is not present. i.e. treat it as a miss | ||
if "no-cache" not in cache_control_headers: | ||
ttl, cached = await backend.get_with_ttl(cache_key) | ||
etag = f"W/{hash(cached)}" | ||
response_headers["Cache-Control"].add(f"max-age={ttl}") | ||
response_headers["Etag"] = {f"ETag={etag}"} | ||
except Exception: | ||
logger.warning( | ||
f"Error retrieving cache key '{cache_key}' from backend:", | ||
exc_info=True, | ||
) | ||
ttl, cached = 0, None | ||
|
||
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) | ||
|
||
try: | ||
await backend.set(cache_key, to_cache, expire) | ||
# no-store: do not store the value in cache | ||
if "no-store" not in cache_control_headers: | ||
await backend.set(cache_key, to_cache, expire) | ||
response_headers["Cache-Control"].add(f"max-age={expire}") | ||
response_headers["Etag"] = {f"W/{hash(to_cache)}"} | ||
except Exception: | ||
logger.warning( | ||
f"Error setting cache key '{cache_key}' in backend:", | ||
|
@@ -198,25 +226,22 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R: | |
if response: | ||
response.headers.update( | ||
{ | ||
"Cache-Control": f"max-age={expire}", | ||
"ETag": f"W/{hash(to_cache)}", | ||
**{header_key: ",".join(sorted(header_val)) for header_key, header_val in response_headers.items()}, | ||
cache_status_header: "MISS", | ||
} | ||
) | ||
|
||
else: # cache hit | ||
if response: | ||
etag = f"W/{hash(cached)}" | ||
response.headers.update( | ||
{ | ||
"Cache-Control": f"max-age={ttl}", | ||
"ETag": etag, | ||
**{header_key: ",".join(sorted(header_val)) for header_key, header_val in response_headers.items()}, | ||
cache_status_header: "HIT", | ||
} | ||
) | ||
|
||
if_none_match = request and request.headers.get("if-none-match") | ||
if if_none_match == etag: | ||
if "Etag" in response_headers and if_none_match == response_headers["Etag"]: | ||
response.status_code = HTTP_304_NOT_MODIFIED | ||
return response | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we can omit lowecasing since FastAPI uses starlette where headers are case-insensitive https://fastapi.tiangolo.com/tutorial/header-params/?h=insensitive#automatic-conversion
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, it looks redundant if Fastapi takes care of it. I pushed the fix.