
"Air is built on FastAPI, so we could use [pyinstrument's instructions](https://pyinstrument.readthedocs.io/en/latest/guide.html#profile-a-web-request-in-fastapi) modified. However, because profilers reveal a LOT of internal data, in our example we actively use an environment variable. You will need both `air` and `pyinstrument` to get this working: ```sh # preferred uv add "air[standard]" pyinstrument # old school pip install "air[standard]" pyinstrument ```"
"import asyncio from os import getenv import air from pyinstrument import Profiler app = air.Air() # Use an environment variable to control if we are profiling # This is a value that should never be set in production if getenv("PROFILING"): @app.middleware("http") async def profile_request(request: air.Request, call_next): profiling = request.query_params.get("profile", False) if profiling: profiler = Profiler() profiler.start() await call_next(request) profiler.stop() return air.responses.HTMLResponse(profiler.output_html()) else: return await call_next(request)"
"@app.page async def index(pause: float = 0): if pause: await asyncio.sleep(pause) title = f"Pausing for {pause} seconds" return air.layouts.mvpcss( air.Title(title), air.H1(title), # Provide three options for testing the profiler air.P('Using asyncio.sleep to simulate bottlenecks'), air.Ol( air.Li( air.A( f"Pause for 0.1 seconds", href="/?profile=1&pause=0.1", target="_blank", ) ), air.Li( air.A( f"Pause for 0.3 seconds", href="/?profile=1&pause=0.3", target="_blank", ) ), air.Li( air.A( f"Pause for 1.0 seconds", href="/?profile=1&pause=1.0", target="_blank", ) ), ),"
Air apps can use pyinstrument with a drop-in HTTP middleware to profile individual requests. Install air and pyinstrument, guard profiling behind an environment variable to avoid exposing internal data in production, and enable profiling per request with a query parameter. The middleware starts the Profiler when ?profile=1 is present, awaits the request, stops the profiler, and returns profiler.output_html() as an HTMLResponse. A sample page simulates bottlenecks with asyncio.sleep and provides links for 0.1, 0.3, and 1.0 second pauses to exercise the profiler in controlled scenarios.
Read at daniel.feldroy.com
Unable to calculate read time
Collection
[
|
...
]