Skip to content

Commit 72552af

Browse files
committed
client side cache middleware created and added
1 parent 2720c25 commit 72552af

File tree

3 files changed

+70
-2
lines changed

3 files changed

+70
-2
lines changed

src/app/core/cache.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,13 @@
88
from fastapi import Request, Response
99
from redis.asyncio import Redis, ConnectionPool
1010
from sqlalchemy.orm import class_mapper, DeclarativeBase
11+
from fastapi import FastAPI
12+
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
1113

1214
from app.core.exceptions import CacheIdentificationInferenceError, InvalidRequestError
1315

16+
# --------------- server side caching ---------------
17+
1418
pool: ConnectionPool | None = None
1519
client: Redis | None = None
1620

@@ -285,3 +289,59 @@ async def inner(request: Request, *args, **kwargs) -> Response:
285289
return inner
286290

287291
return wrapper
292+
293+
# --------------- client side caching ---------------
294+
295+
class ClientCacheMiddleware(BaseHTTPMiddleware):
296+
"""
297+
Middleware to set the `Cache-Control` header for client-side caching on all responses.
298+
299+
Parameters
300+
----------
301+
app: FastAPI
302+
The FastAPI application instance.
303+
max_age: int, optional
304+
Duration (in seconds) for which the response should be cached. Defaults to 60 seconds.
305+
306+
Attributes
307+
----------
308+
max_age: int
309+
Duration (in seconds) for which the response should be cached.
310+
311+
Methods
312+
-------
313+
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
314+
Process the request and set the `Cache-Control` header in the response.
315+
316+
Note
317+
----
318+
- The `Cache-Control` header instructs clients (e.g., browsers) to cache the response for the specified duration.
319+
"""
320+
321+
def __init__(self, app: FastAPI, max_age: int = 60) -> None:
322+
super().__init__(app)
323+
self.max_age = max_age
324+
325+
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
326+
"""
327+
Process the request and set the `Cache-Control` header in the response.
328+
329+
Parameters
330+
----------
331+
request: Request
332+
The incoming request.
333+
call_next: RequestResponseEndpoint
334+
The next middleware or route handler in the processing chain.
335+
336+
Returns
337+
-------
338+
Response
339+
The response object with the `Cache-Control` header set.
340+
341+
Note
342+
----
343+
- This method is automatically called by Starlette for processing the request-response cycle.
344+
"""
345+
response: Response = await call_next(request)
346+
response.headers['Cache-Control'] = f"public, max-age={self.max_age}"
347+
return response

src/app/core/config.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,18 @@ class RedisCacheSettings(BaseSettings):
7272
REDIS_CACHE_URL: str = f"redis://{REDIS_CACHE_HOST}:{REDIS_CACHE_PORT}"
7373

7474

75+
class ClientSideCacheSettings(BaseSettings):
76+
CLIENT_CACHE_MAX_AGE: int = config("CLIENT_CACHE_MAX_AGE", default=60)
77+
78+
7579
class Settings(
7680
AppSettings,
7781
PostgresSettings,
7882
CryptSettings,
7983
FirstUserSettings,
8084
TestSettings,
81-
RedisCacheSettings
85+
RedisCacheSettings,
86+
ClientSideCacheSettings
8287
):
8388
pass
8489

src/app/main.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from app.core.database import Base
55
from app.core.database import async_engine as engine
6-
from app.core.config import settings, DatabaseSettings, RedisCacheSettings, AppSettings
6+
from app.core.config import settings, DatabaseSettings, RedisCacheSettings, AppSettings, ClientSideCacheSettings
77
from app.api import router
88
from app.core import cache
99

@@ -44,6 +44,9 @@ def create_application() -> FastAPI:
4444
application.add_event_handler("startup", create_redis_cache_pool)
4545
application.add_event_handler("shutdown", close_redis_cache_pool)
4646

47+
if isinstance(settings, ClientSideCacheSettings):
48+
application.add_middleware(cache.ClientCacheMiddleware, max_age=60)
49+
4750
return application
4851

4952

0 commit comments

Comments
 (0)