kocraft-backend/Craft/middleware/processtime_middlewares.py

27 lines
845 B
Python
Raw Normal View History

2024-07-15 08:47:42 +00:00
import fastapi
import datetime
from fastapi import FastAPI, Request
from fastapi.middleware import Middleware
from fastapi.responses import JSONResponse
from typing import Any, Dict, Callable, Coroutine
def init_processtimemiddleware(app: FastAPI):
@app.middleware("http")
async def process_time_middleware(request: Request, call_next):
try:
start_time = datetime.datetime.now()
response = await call_next(request)
end_time = datetime.datetime.now()
response.headers["process-Time"] = (
str(round((end_time - start_time).total_seconds(), 1)) + "s"
)
return response
except Exception as e:
return JSONResponse(
status_code=500, content={"message": "Internal Server Error"}
)
return app