|
6 | 6 | from fastapi import Request, Response |
7 | 7 | from fastapi.encoders import jsonable_encoder |
8 | 8 | from redis.asyncio import Redis, ConnectionPool |
9 | | -from fastapi import FastAPI |
10 | | -from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint |
11 | 9 |
|
12 | 10 | from app.core.exceptions import CacheIdentificationInferenceError, InvalidRequestError |
13 | 11 |
|
14 | | -# --------------- server side caching --------------- |
15 | | - |
16 | 12 | pool: ConnectionPool | None = None |
17 | 13 | client: Redis | None = None |
18 | 14 |
|
@@ -334,59 +330,3 @@ async def inner(request: Request, *args, **kwargs) -> Response: |
334 | 330 | return inner |
335 | 331 |
|
336 | 332 | 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 |
0 commit comments