Skip to content

Commit e50ad8f

Browse files
committed
middleware folder, client side cache moved from cache.py to a file in middleware
1 parent f72dd9d commit e50ad8f

File tree

3 files changed

+59
-61
lines changed

3 files changed

+59
-61
lines changed

src/app/core/cache.py

Lines changed: 0 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,9 @@
66
from fastapi import Request, Response
77
from fastapi.encoders import jsonable_encoder
88
from redis.asyncio import Redis, ConnectionPool
9-
from fastapi import FastAPI
10-
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
119

1210
from app.core.exceptions import CacheIdentificationInferenceError, InvalidRequestError
1311

14-
# --------------- server side caching ---------------
15-
1612
pool: ConnectionPool | None = None
1713
client: Redis | None = None
1814

@@ -334,59 +330,3 @@ async def inner(request: Request, *args, **kwargs) -> Response:
334330
return inner
335331

336332
return wrapper
337-
338-
# --------------- client side caching ---------------
339-
340-
class ClientCacheMiddleware(BaseHTTPMiddleware):
341-
"""
342-
Middleware to set the `Cache-Control` header for client-side caching on all responses.
343-
344-
Parameters
345-
----------
346-
app: FastAPI
347-
The FastAPI application instance.
348-
max_age: int, optional
349-
Duration (in seconds) for which the response should be cached. Defaults to 60 seconds.
350-
351-
Attributes
352-
----------
353-
max_age: int
354-
Duration (in seconds) for which the response should be cached.
355-
356-
Methods
357-
-------
358-
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
359-
Process the request and set the `Cache-Control` header in the response.
360-
361-
Note
362-
----
363-
- The `Cache-Control` header instructs clients (e.g., browsers) to cache the response for the specified duration.
364-
"""
365-
366-
def __init__(self, app: FastAPI, max_age: int = 60) -> None:
367-
super().__init__(app)
368-
self.max_age = max_age
369-
370-
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
371-
"""
372-
Process the request and set the `Cache-Control` header in the response.
373-
374-
Parameters
375-
----------
376-
request: Request
377-
The incoming request.
378-
call_next: RequestResponseEndpoint
379-
The next middleware or route handler in the processing chain.
380-
381-
Returns
382-
-------
383-
Response
384-
The response object with the `Cache-Control` header set.
385-
386-
Note
387-
----
388-
- This method is automatically called by Starlette for processing the request-response cycle.
389-
"""
390-
response: Response = await call_next(request)
391-
response.headers['Cache-Control'] = f"public, max-age={self.max_age}"
392-
return response

src/app/core/setup.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
EnvironmentOption,
2323
EnvironmentSettings
2424
)
25+
from app.middleware.client_cache_middleware import ClientCacheMiddleware
2526

2627
# -------------- database --------------
2728
async def create_tables():
@@ -138,7 +139,7 @@ def create_application(router: APIRouter, settings, **kwargs) -> FastAPI:
138139
application.add_event_handler("shutdown", close_redis_cache_pool)
139140

140141
if isinstance(settings, ClientSideCacheSettings):
141-
application.add_middleware(cache.ClientCacheMiddleware, max_age=settings.CLIENT_CACHE_MAX_AGE)
142+
application.add_middleware(ClientCacheMiddleware, max_age=settings.CLIENT_CACHE_MAX_AGE)
142143

143144
if isinstance(settings, RedisQueueSettings):
144145
application.add_event_handler("startup", create_redis_queue_pool)
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from fastapi import FastAPI, Request, Response
2+
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
3+
4+
5+
class ClientCacheMiddleware(BaseHTTPMiddleware):
6+
"""
7+
Middleware to set the `Cache-Control` header for client-side caching on all responses.
8+
9+
Parameters
10+
----------
11+
app: FastAPI
12+
The FastAPI application instance.
13+
max_age: int, optional
14+
Duration (in seconds) for which the response should be cached. Defaults to 60 seconds.
15+
16+
Attributes
17+
----------
18+
max_age: int
19+
Duration (in seconds) for which the response should be cached.
20+
21+
Methods
22+
-------
23+
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
24+
Process the request and set the `Cache-Control` header in the response.
25+
26+
Note
27+
----
28+
- The `Cache-Control` header instructs clients (e.g., browsers) to cache the response for the specified duration.
29+
"""
30+
31+
def __init__(self, app: FastAPI, max_age: int = 60) -> None:
32+
super().__init__(app)
33+
self.max_age = max_age
34+
35+
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
36+
"""
37+
Process the request and set the `Cache-Control` header in the response.
38+
39+
Parameters
40+
----------
41+
request: Request
42+
The incoming request.
43+
call_next: RequestResponseEndpoint
44+
The next middleware or route handler in the processing chain.
45+
46+
Returns
47+
-------
48+
Response
49+
The response object with the `Cache-Control` header set.
50+
51+
Note
52+
----
53+
- This method is automatically called by Starlette for processing the request-response cycle.
54+
"""
55+
response: Response = await call_next(request)
56+
response.headers['Cache-Control'] = f"public, max-age={self.max_age}"
57+
return response

0 commit comments

Comments
 (0)