-
Notifications
You must be signed in to change notification settings - Fork 10
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
browser cache #841
Merged
Merged
browser cache #841
Changes from 3 commits
Commits
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 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 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 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
92 changes: 92 additions & 0 deletions
92
backend_py/primary/primary/middleware/add_browser_cache.py
This file contains 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 |
---|---|---|
@@ -0,0 +1,92 @@ | ||
from functools import wraps | ||
from contextvars import ContextVar | ||
from typing import Dict, Any, Callable, Awaitable, Union, Never | ||
|
||
from starlette.datastructures import MutableHeaders | ||
from starlette.types import ASGIApp, Scope, Receive, Send, Message | ||
from primary.config import DEFAULT_CACHE_MAX_AGE, DEFAULT_STALE_WHILE_REVALIDATE | ||
|
||
# Initialize with a factory function to ensure a new dict for each context | ||
def get_default_context() -> Dict[str, Any]: | ||
return {"max_age": DEFAULT_CACHE_MAX_AGE, "stale_while_revalidate": DEFAULT_STALE_WHILE_REVALIDATE} | ||
|
||
|
||
cache_context: ContextVar[Dict[str, Any]] = ContextVar("cache_context", default=get_default_context()) | ||
|
||
|
||
def add_custom_cache_time(max_age_s: int, stale_while_revalidate_s: int = 0) -> Callable: | ||
""" | ||
Decorator that sets a custom browser cache time for the endpoint response. | ||
|
||
Args: | ||
max_age_s (int): The maximum age in seconds for the cache | ||
stale_while_revalidate_s (int): The stale-while-revalidate time in seconds | ||
|
||
Example: | ||
@add_custom_cache_time(300, 600) # 5 minutes max age, 10 minutes stale-while-revalidate | ||
async def my_endpoint(): | ||
return {"data": "some_data"} | ||
""" | ||
|
||
def decorator(func: Callable) -> Callable: | ||
@wraps(func) | ||
async def wrapper(*args: Any, **kwargs: Any) -> Callable: | ||
context = cache_context.get() | ||
context["max_age"] = max_age_s | ||
context["stale_while_revalidate"] = stale_while_revalidate_s | ||
|
||
return await func(*args, **kwargs) | ||
|
||
return wrapper | ||
|
||
return decorator | ||
|
||
|
||
def no_cache(func: Callable) -> Callable: | ||
""" | ||
Decorator that explicitly disables browser caching for the endpoint response. | ||
|
||
Example: | ||
@no_cache | ||
async def my_endpoint(): | ||
return {"data": "some_data"} | ||
""" | ||
|
||
@wraps(func) | ||
async def wrapper(*args: Any, **kwargs: Any) -> Callable: | ||
context = cache_context.get() | ||
context["max_age"] = 0 | ||
context["stale_while_revalidate"] = 0 | ||
|
||
return await func(*args, **kwargs) | ||
|
||
return wrapper | ||
|
||
|
||
class AddBrowserCacheMiddleware: | ||
""" | ||
Adds cache-control to the response headers | ||
""" | ||
|
||
def __init__(self, app: ASGIApp) -> None: | ||
self.app = app | ||
|
||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
if scope["type"] != "http": | ||
return await self.app(scope, receive, send) | ||
|
||
# Set initial context and store token | ||
cache_context.set(get_default_context()) | ||
|
||
async def send_with_cache_header(message: Message) -> None: | ||
if message["type"] == "http.response.start": | ||
headers = MutableHeaders(scope=message) | ||
context = cache_context.get() | ||
cache_control_str = ( | ||
f"max-age={context['max_age']}, stale-while-revalidate={context['stale_while_revalidate']}, private" | ||
) | ||
headers.append("cache-control", cache_control_str) | ||
|
||
await send(message) | ||
|
||
await self.app(scope, receive, send_with_cache_header) |
This file contains 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 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 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
Oops, something went wrong.
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.
This probably could be cached. It very rarely changes - and when it does the user has to wait for access to sync through infrastructure and Azure anyway. E.g.
max-age
of one minute and a defaultstale-while-revalidate
of one day?