add elapsed processing time to response
This commit is contained in:
parent
0a21cb4420
commit
c823c51721
2 changed files with 31 additions and 1 deletions
26
unwind/middleware/responsetime.py
Normal file
26
unwind/middleware/responsetime.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
from time import perf_counter
|
||||
|
||||
from starlette.datastructures import MutableHeaders
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
|
||||
class ResponseTimeMiddleware:
|
||||
def __init__(self, app: ASGIApp, header_name: str = "Elapsed") -> None:
|
||||
self.app = app
|
||||
self.header_name = header_name
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
start = perf_counter()
|
||||
|
||||
if scope["type"] not in ("http", "websocket"):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
async def send_wrapper(message: Message) -> None:
|
||||
if message["type"] == "http.response.start":
|
||||
headers = MutableHeaders(scope=message)
|
||||
elapsed = perf_counter() - start
|
||||
headers.append(self.header_name, str(elapsed))
|
||||
await send(message)
|
||||
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
|
|
@ -19,6 +19,7 @@ from starlette.routing import Mount, Route
|
|||
|
||||
from . import config, db
|
||||
from .db import close_connection_pool, find_ratings, open_connection_pool
|
||||
from .middleware.responsetime import ResponseTimeMiddleware
|
||||
from .models import Movie, asplain
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
|
@ -190,5 +191,8 @@ def create_app():
|
|||
],
|
||||
),
|
||||
],
|
||||
middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())],
|
||||
middleware=[
|
||||
Middleware(ResponseTimeMiddleware, header_name="Unwind-Elapsed"),
|
||||
Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()),
|
||||
],
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue