Skip to content

Commit fe2ee3f

Browse files
wip
1 parent fdf62e1 commit fe2ee3f

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

backend_py/primary/primary/middleware/add_browser_cache.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
from functools import wraps
22
from contextvars import ContextVar
3-
from typing import Dict, Any
3+
from typing import Dict, Any, Callable, TypeVar, Awaitable
44

55
from starlette.datastructures import MutableHeaders
6+
from starlette.types import ASGIApp, Scope, Receive, Send, Message
67
from primary.config import DEFAULT_CACHE_MAX_AGE, DEFAULT_STALE_WHILE_REVALIDATE
78

9+
T = TypeVar("T")
810

911
# Initialize with a factory function to ensure a new dict for each context
1012
def get_default_context() -> Dict[str, Any]:
@@ -14,7 +16,9 @@ def get_default_context() -> Dict[str, Any]:
1416
cache_context: ContextVar[Dict[str, Any]] = ContextVar("cache_context", default=get_default_context())
1517

1618

17-
def add_custom_cache_time(max_age: int, stale_while_revalidate: int = 0) -> Any:
19+
def add_custom_cache_time(
20+
max_age: int, stale_while_revalidate: int = 0
21+
) -> Callable[[Callable[..., Awaitable[T]]], Callable[..., Awaitable[T]]]:
1822
"""
1923
Decorator that sets a custom cache time for the endpoint response.
2024
@@ -28,9 +32,9 @@ async def my_endpoint():
2832
return {"data": "some_data"}
2933
"""
3034

31-
def decorator(func):
35+
def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
3236
@wraps(func)
33-
async def wrapper(*args, **kwargs):
37+
async def wrapper(*args: Any, **kwargs: Any) -> T:
3438
context = cache_context.get()
3539
context["max_age"] = max_age
3640
context["stale_while_revalidate"] = stale_while_revalidate
@@ -47,17 +51,17 @@ class AddBrowserCacheMiddleware:
4751
Adds cache-control to the response headers
4852
"""
4953

50-
def __init__(self, app):
54+
def __init__(self, app: ASGIApp) -> None:
5155
self.app = app
5256

53-
async def __call__(self, scope, receive, send) -> None:
57+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
5458
if scope["type"] != "http":
5559
return await self.app(scope, receive, send)
5660

5761
# Set initial context and store token
5862
cache_context.set(get_default_context())
5963

60-
async def send_with_cache_header(message) -> None:
64+
async def send_with_cache_header(message: Message) -> None:
6165
if message["type"] == "http.response.start":
6266
headers = MutableHeaders(scope=message)
6367
context = cache_context.get()

0 commit comments

Comments
 (0)