Debian Codegraph @

docs/examples/middleware/request_timing.py

raw
1 import time
2
3 from litestar.datastructures import MutableScopeHeaders
4 from litestar.enums import ScopeType
5 from litestar.middleware import ASGIMiddleware
6 from litestar.types import ASGIApp, Message, Receive, Scope, Send
7
8
9 class ProcessTimeHeader(ASGIMiddleware):
10 scopes = (ScopeType.HTTP, ScopeType.ASGI)
11
12 async def handle(self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) -> None:
13 start_time = time.monotonic()
14
15 async def send_wrapper(message: Message) -> None:
16 if message["type"] == "http.response.start":
17 process_time = time.monotonic() - start_time
18 headers = MutableScopeHeaders.from_message(message=message)
19 headers["X-Process-Time"] = str(process_time)
20 await send(message)
21
22 await next_app(scope, receive, send_wrapper)