Application Profiler — Werkzeug Documentation (3.1.x)

# Application Profiler

This module provides a middleware that profiles each request with the `cProfile` module. This can help identify bottlenecks in your code that may be slowing down your application.

class werkzeug.middleware.profiler.ProfilerMiddleware(app, stream=sys.stdout, sort_by=('time', 'calls'), restrictions=(), profile_dir=None, filename_format='{method}.{path}.{elapsed:.0f}ms.{time:.0f}.prof')

  Wrap a WSGI application and profile the execution of each request. Responses are buffered so that timings are more exact.

  If `stream` is given, `pstats.Stats` are written to it after each request. If `profile_dir` is given, `cProfile` data files are saved to that directory, one file per request.

  The filename can be customized by passing `filename_format`. If it is a string, it will be formatted using `str.format()` with the following fields available:

  - `{method}` - The request method; GET, POST, etc.

  - `{path}` - The request path or ‘root’ should one not exist.

  - `{elapsed}` - The elapsed time of the request in milliseconds.

  - `{time}` - The time of the request.

  If it is a callable, it will be called with the WSGI `environ` and be expected to return a filename string. The `environ` dictionary will also have the `"werkzeug.profiler"` key populated with a dictionary containing the following fields (more may be added in the future): - `{elapsed}` - The elapsed time of the request in milliseconds. - `{time}` - The time of the request.

  Parameters:

    - app (WSGIApplication) – The WSGI application to wrap.

    - stream (t.IO[str] | None) – Write stats to this stream. Disable with `None`.

    - sort_by (t.Iterable[str]) – A tuple of columns to sort stats by. See `pstats.Stats.sort_stats()`.

    - restrictions (t.Iterable[str | int | float]) – A tuple of restrictions to filter stats by. See `pstats.Stats.print_stats()`.

    - profile_dir (str | None) – Save profile data files to this directory.

    - filename_format (str) – Format string for profile data file names, or a callable returning a name. See explanation above.

      from werkzeug.middleware.profiler import ProfilerMiddleware
      app = ProfilerMiddleware(app)

  Changelog

  Changed in version 3.0: Added the `"werkzeug.profiler"` key to the `filename_format(environ)` parameter with the `elapsed` and `time` fields.

  Changed in version 0.15: Stats are written even if `profile_dir` is given, and can be disable by passing `stream=None`.

  Added in version 0.15: Added `filename_format`.

  Added in version 0.9: Added `restrictions` and `profile_dir`.