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