-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathprofiler.py
More file actions
28 lines (22 loc) · 847 Bytes
/
profiler.py
File metadata and controls
28 lines (22 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from __future__ import annotations
from fastapi import Request
from pyinstrument import Profiler
from starlette.middleware.base import (
BaseHTTPMiddleware,
RequestResponseEndpoint,
)
from starlette.responses import HTMLResponse, Response
class ProfilingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
if request.query_params.get("pyprofile") == "true":
profiler = Profiler(interval=0.001, async_mode="enabled")
profiler.start()
await call_next(request)
profiler.stop()
return HTMLResponse(
profiler.output_html(),
headers={"Content-Disposition": "attachment; filename=profile.html"},
)
return await call_next(request)