generated from coulomb/repo-seed
Optimize dashboard overview loading
This commit is contained in:
16
api/main.py
16
api/main.py
@@ -1,5 +1,6 @@
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
@@ -26,26 +27,37 @@ class ETagMiddleware(BaseHTTPMiddleware):
|
||||
"""Add ETag + conditional-GET (304) support to all JSON GET responses."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
started = time.perf_counter()
|
||||
response = await call_next(request)
|
||||
if request.method != "GET":
|
||||
response.headers["X-StateHub-Elapsed-Ms"] = f"{(time.perf_counter() - started) * 1000:.1f}"
|
||||
return response
|
||||
if "application/json" not in response.headers.get("content-type", ""):
|
||||
response.headers["X-StateHub-Elapsed-Ms"] = f"{(time.perf_counter() - started) * 1000:.1f}"
|
||||
return response
|
||||
|
||||
body_parts = []
|
||||
async for chunk in response.body_iterator:
|
||||
body_parts.append(chunk)
|
||||
body = b"".join(body_parts)
|
||||
elapsed_ms = f"{(time.perf_counter() - started) * 1000:.1f}"
|
||||
|
||||
etag = '"' + hashlib.md5(body, usedforsecurity=False).hexdigest() + '"'
|
||||
if request.headers.get("if-none-match") == etag:
|
||||
return StarletteResponse(
|
||||
status_code=304,
|
||||
headers={"ETag": etag, "Cache-Control": "no-cache"},
|
||||
headers={
|
||||
"ETag": etag,
|
||||
"Cache-Control": "no-cache",
|
||||
"X-StateHub-Elapsed-Ms": elapsed_ms,
|
||||
"X-StateHub-Response-Bytes": "0",
|
||||
},
|
||||
)
|
||||
|
||||
headers = {k: v for k, v in response.headers.items() if k.lower() != "content-length"}
|
||||
headers["ETag"] = etag
|
||||
headers["X-StateHub-Elapsed-Ms"] = elapsed_ms
|
||||
headers["X-StateHub-Response-Bytes"] = str(len(body))
|
||||
if not any(k.lower() == "cache-control" for k in headers):
|
||||
headers["Cache-Control"] = "no-cache"
|
||||
return StarletteResponse(
|
||||
@@ -84,7 +96,7 @@ app.add_middleware(
|
||||
allow_origins=_cors_origins,
|
||||
allow_methods=["GET", "POST", "PATCH", "DELETE", "PUT"],
|
||||
allow_headers=["Content-Type", "If-None-Match"],
|
||||
expose_headers=["ETag"],
|
||||
expose_headers=["ETag", "X-StateHub-Elapsed-Ms", "X-StateHub-Response-Bytes", "X-StateHub-Cache"],
|
||||
)
|
||||
|
||||
app.include_router(domains.router)
|
||||
|
||||
Reference in New Issue
Block a user