diff --git a/src/titiler/core/tests/test_cache_middleware.py b/src/titiler/core/tests/test_cache_middleware.py index b90e2698e..fc829b4dd 100644 --- a/src/titiler/core/tests/test_cache_middleware.py +++ b/src/titiler/core/tests/test_cache_middleware.py @@ -5,6 +5,7 @@ from fastapi import FastAPI, Path +from starlette.responses import Response from starlette.testclient import TestClient @@ -36,9 +37,19 @@ async def tiles( """tiles.""" return "yeah" + @app.get("/emptytiles/{z}/{x}/{y}") + async def emptytiles( + z: int = Path(..., ge=0, le=30, description="Mercator tiles's zoom level"), + x: int = Path(..., description="Mercator tiles's column"), + y: int = Path(..., description="Mercator tiles's row"), + ): + """tiles.""" + return Response(status_code=404) + app.add_middleware( CacheControlMiddleware, cachecontrol="public", + cachecontrol_max_http_code=400, exclude_path={r"/route1", r"/route2", r"/tiles/[0-1]/.+"}, ) @@ -58,3 +69,6 @@ async def tiles( response = client.get("/tiles/3/1/1") assert response.headers["Cache-Control"] == "public" + + response = client.get("/emptytiles/3/1/1") + assert not response.headers.get("Cache-Control") diff --git a/src/titiler/core/titiler/core/middleware.py b/src/titiler/core/titiler/core/middleware.py index 8496f73a3..be655304e 100644 --- a/src/titiler/core/titiler/core/middleware.py +++ b/src/titiler/core/titiler/core/middleware.py @@ -19,6 +19,7 @@ def __init__( self, app: ASGIApp, cachecontrol: Optional[str] = None, + cachecontrol_max_http_code: Optional[int] = 500, exclude_path: Optional[Set[str]] = None, ) -> None: """Init Middleware. @@ -31,6 +32,7 @@ def __init__( """ super().__init__(app) self.cachecontrol = cachecontrol + self.cachecontrol_max_http_code = cachecontrol_max_http_code self.exclude_path = exclude_path or set() async def dispatch(self, request: Request, call_next): @@ -41,7 +43,10 @@ async def dispatch(self, request: Request, call_next): if re.match(path, request.url.path): return response - if request.method in ["HEAD", "GET"] and response.status_code < 500: + if ( + request.method in ["HEAD", "GET"] + and response.status_code < self.cachecontrol_max_http_code + ): response.headers["Cache-Control"] = self.cachecontrol return response