| 1 |
import time |
| 2 |
|
| 3 |
from litestar import Litestar, get |
| 4 |
from litestar.datastructures import MutableScopeHeaders |
| 5 |
from litestar.middleware import ASGIMiddleware |
| 6 |
from litestar.types import ASGIApp, Message, Receive, Scope, Send |
| 7 |
|
| 8 |
|
| 9 |
class ProcessTimeMiddleware(ASGIMiddleware): |
| 10 |
async def handle(self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) -> None: |
| 11 |
start_time = time.monotonic() |
| 12 |
|
| 13 |
async def send_wrapper(message: Message) -> None: |
| 14 |
if message["type"] == "http.response.start": |
| 15 |
headers = MutableScopeHeaders.from_message(message=message) |
| 16 |
headers["x-process-time"] = f"{time.monotonic() - start_time:.4f}" |
| 17 |
await send(message) |
| 18 |
|
| 19 |
await next_app(scope, receive, send_wrapper) |
| 20 |
|
| 21 |
|
| 22 |
@get("/") |
| 23 |
async def index() -> dict[str, str]: |
| 24 |
return {"hello": "world"} |
| 25 |
|
| 26 |
|
| 27 |
app = Litestar(route_handlers=[index], middleware=[ProcessTimeMiddleware()]) |