caching added #140

Merged
genja merged 4 commits from caching into dev 2026-06-12 18:51:40 +02:00
2 changed files with 59 additions and 0 deletions
+7
View File
@@ -17,6 +17,8 @@ from inse.works.service import router as works_service_router
from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
#caching
from inse.middleware.etag_cache import ETagCacheMiddleware
from . import config
from .service import router as service_router
from .account.service import router as account_router
@@ -43,12 +45,17 @@ app.include_router(funders_service_router)
app.include_router(service_router)
app.include_router(account_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=300 # 5 minutes expiration time
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["ETag"]
)
@@ -0,0 +1,52 @@
# middleware/etag_cache.py
import hashlib, json, time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
class ETagCacheMiddleware(BaseHTTPMiddleware):
def __init__(self, app, ttl: int = 60):
super().__init__(app)
self.ttl = ttl # timeout in seconds
self.cache: dict[str, dict] = {} # key → {body, etag, expires}
def _cache_key(self, request: Request) -> str:
# Include query params and relevant headers in the key
return f"{request.url.path}?{request.url.query}"
async def dispatch(self, request: Request, call_next):
if request.method != "GET":
return await call_next(request)
key = self._cache_key(request)
entry = self.cache.get(key)
client_etag = request.headers.get("if-none-match")
# Cache hit + not expired
if entry and time.time() < entry["expires"]:
if client_etag == entry["etag"]:
return Response(status_code=304, headers={"ETag": entry["etag"]})
# Client has stale ETag - return fresh cached body
return Response(
content=entry["body"],
media_type="application/json",
headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
)
# Cache miss or expired → hit the actual route
response = await call_next(request)
body = b"".join([chunk async for chunk in response.body_iterator])
etag = f'"{hashlib.md5(body).hexdigest()}"'
self.cache[key] = {
"body": body,
"etag": etag,
"expires": time.time() + self.ttl
}
return Response(
content=body,
status_code=response.status_code,
media_type="application/json",
headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
)