From a41c4d7940de976f6d849cdc7bfcf37137590815 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Sat, 22 Mar 2025 01:19:11 +0200 Subject: [PATCH] docs_src/middleware/tutorial002.py: new tutorial source code added --- docs_src/middleware/tutorial002.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 docs_src/middleware/tutorial002.py diff --git a/docs_src/middleware/tutorial002.py b/docs_src/middleware/tutorial002.py new file mode 100644 index 000000000..8c0526cc1 --- /dev/null +++ b/docs_src/middleware/tutorial002.py @@ -0,0 +1,22 @@ +import time + +from fastapi import FastAPI, Request, Response +from starlette.middleware.base import BaseHTTPMiddleware + + +class ProcessTimeHeaderMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + start_time = time.perf_counter() + response: Response = await call_next(request) + process_time = time.perf_counter() - start_time + response.headers["X-Process-Time"] = str(process_time) + return response + + +app = FastAPI() +app.add_middleware(ProcessTimeHeaderMiddleware) + + +@app.get("/") +def hello(): + return {"hello": "world"} \ No newline at end of file