use Scalene for FastAPI profiling

731 Views Asked by At

I'm currently trying to profile my FastAPI endpoints using Scalene. my code looks like this. I have a profiling middleware like this:

class ScaleneProfilerMiddleware(BaseHTTPMiddleware):

    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        with _profiler() as profiler:
            response = await call_next(request)
            return _handle_response(profiler)

and the _profiler() function should be something like this:

@contextmanager
def _profiler():
    profiler = Scalene()
    try:
        profiler.start()
        yield profiler
    finally:
        profiler.stop()

and I like to generate an HTML response right away using the _handle_response(response, profiler) which is something like this:

def _handle_response(
    profiler: Scalene
) -> Response:
    return HTMLResponse(profiler.generate_html())

I couldn't find any example like this so I'm wondering if this is possible at the moment

0

There are 0 best solutions below