From: Michael Tremer Date: Thu, 10 Jul 2025 13:22:55 +0000 (+0000) Subject: api: Add processing time to the response headers X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c4c36c81cfcb843146e0e0ebdf5bca1af252b127;p=pbs.git api: Add processing time to the response headers Signed-off-by: Michael Tremer --- diff --git a/src/api/__init__.py b/src/api/__init__.py index 27bd851e..813f9e23 100644 --- a/src/api/__init__.py +++ b/src/api/__init__.py @@ -20,6 +20,7 @@ import fastapi import fastapi.middleware.cors +import time from .. import Backend @@ -36,6 +37,25 @@ app = fastapi.FastAPI( debug = True, ) +@app.middleware("http") +async def add_process_time_header(request: fastapi.Request, call_next): + """ + Add the processing time of the request to the response headers. + """ + # 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 + # Add CORS app.add_middleware( fastapi.middleware.cors.CORSMiddleware,