Skip to content

Commit

Permalink
Make http error cache control behavior configurable. (#444)
Browse files Browse the repository at this point in the history
* Make http error cache control behavior configurable.

* Update parameter naming as requested by @vincentsarago.
  • Loading branch information
sharkinsspatial authored Mar 3, 2022
1 parent 666cfa6 commit 7b8d4d9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/titiler/core/tests/test_cache_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from fastapi import FastAPI, Path

from starlette.responses import Response
from starlette.testclient import TestClient


Expand Down Expand Up @@ -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]/.+"},
)

Expand All @@ -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")
7 changes: 6 additions & 1 deletion src/titiler/core/titiler/core/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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):
Expand All @@ -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
Expand Down

0 comments on commit 7b8d4d9

Please sign in to comment.