debug = True,
)
app.add_middleware(middlewares.DatabaseSessionMiddleware)
+app.add_middleware(middlewares.ProcessingTimeMiddleware)
# Initialize the backend
backend = app.state.backend = Backend(
###############################################################################
import fastapi
+import time
class DatabaseSessionMiddleware(fastapi.applications.BaseHTTPMiddleware):
async def dispatch(self, request: fastapi.Request, call_next):
# Acquire a new database session and process the request
async with await backend.db.session() as session:
return await call_next(request)
+
+
+class ProcessingTimeMiddleware(fastapi.applications.BaseHTTPMiddleware):
+ """
+ Adds a new header X-Process-Time that shows
+ how long the API needed to process the request.
+ """
+ async def dispatch(self, request: fastapi.Request, call_next):
+ # Store the start time
+ t_start = time.perf_counter()
+
+ # Continue to run the request...
+ response = await call_next(request)
+
+ # Store the end time
+ t_end = time.perf_counter()
+
+ # Set the process time in the header in milliseconds
+ response.headers["X-Process-Time"] = "%.2fms" % ((t_end - t_start) * 1000.0)
+
+ return response