feat(middleware): add process time header middleware for request timing
Browse files
main.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from contextlib import asynccontextmanager
|
| 4 |
|
|
@@ -7,6 +7,8 @@ from api.routers import memory
|
|
| 7 |
from db.session import create_db_and_tables
|
| 8 |
from core.config import get_settings
|
| 9 |
|
|
|
|
|
|
|
| 10 |
settings = get_settings()
|
| 11 |
|
| 12 |
@asynccontextmanager
|
|
@@ -25,7 +27,17 @@ app = FastAPI(
|
|
| 25 |
lifespan=lifespan
|
| 26 |
)
|
| 27 |
|
| 28 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
app.add_middleware(
|
| 30 |
CORSMiddleware,
|
| 31 |
allow_origins=[settings.FRONTEND_URL, "http://127.0.0.1:3000"],
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from contextlib import asynccontextmanager
|
| 4 |
|
|
|
|
| 7 |
from db.session import create_db_and_tables
|
| 8 |
from core.config import get_settings
|
| 9 |
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
settings = get_settings()
|
| 13 |
|
| 14 |
@asynccontextmanager
|
|
|
|
| 27 |
lifespan=lifespan
|
| 28 |
)
|
| 29 |
|
| 30 |
+
# --- Middlewares ---
|
| 31 |
+
|
| 32 |
+
@app.middleware("http")
|
| 33 |
+
async def add_process_time_header(request: Request, call_next):
|
| 34 |
+
start_time = time.time()
|
| 35 |
+
response = await call_next(request)
|
| 36 |
+
process_time = time.time() - start_time
|
| 37 |
+
response.headers["X-Process-Time"] = str(process_time)
|
| 38 |
+
print(f"INFO: Request {request.method} {request.url.path} processed in {process_time:.4f} sec")
|
| 39 |
+
return response
|
| 40 |
+
|
| 41 |
app.add_middleware(
|
| 42 |
CORSMiddleware,
|
| 43 |
allow_origins=[settings.FRONTEND_URL, "http://127.0.0.1:3000"],
|