FastHTML is built on Starlette, so we use Starlette's middleware tooling and then pass in the result. Just make sure you install pyinstrument.
WARNING: NOT FOR PRODUCTION ENVIRONMENTS Including a profiler like this in a production environment is dangerous. As it exposes infrastructure it is highly risky to include in any location where end users can access it.
"""WARNING: NOT FOR PRODUCTION ENVIRONMENTS"""fromfasthtml.commonimport*fromstarlette.middleware.baseimportBaseHTTPMiddlewarefromstarlette.middlewareimportMiddlewaretry:frompyinstrumentimportProfilerexceptImportError:raiseImportError('Please install pyinstrument')classProfileMiddleware(BaseHTTPMiddleware):asyncdefdispatch(self,request,call_next):profiling=request.query_params.get("profile",False)ifprofiling:profiler=Profiler()profiler.start()response=awaitcall_next(request)profiler.stop()returnHTMLResponse(profiler.output_html())returnawaitcall_next(request)app,rt=fast_app(middleware=(Middleware(ProfileMiddleware)))@rt("/")defget():returnTitled("FastHTML",P("Hello, world!"))serve()
To invoke, make any request to your application with the GET parameter
profile=1
and it will print the HTML result from pyinstrument.