WSGI Application Profiler

This module provides a simple WSGI profiler middleware for finding bottlenecks in web application. It uses the profile or cProfile module to do the profiling and writes the stats to the stream provided (defaults to stderr).

Example usage::
from werkzeug.contrib.profiler import ProfilerMiddleware app = ProfilerMiddleware(app)
class werkzeug.contrib.profiler.MergeStream(*streams)

An object that redirects write calls to multiple streams. Use this to log to both sys.stdout and a file:

f = open('profiler.log', 'w')
stream = MergeStream(sys.stdout, f)
profiler = ProfilerMiddleware(app, stream)
class werkzeug.contrib.profiler.ProfilerMiddleware(app, stream=None, sort_by=('time', 'calls'), restrictions=(), profile_dir=None, filename_format='%(method)s.%(path)s.%(elapsed)06dms.%(time)d')

Simple profiler middleware. Wraps a WSGI application and profiles a request. This intentionally buffers the response so that timings are more exact.

By giving the profile_dir argument, pstat.Stats files are saved to that directory, one file per request. Without it, a summary is printed to stream instead.

The file name format 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
  • {time} - the time of the request

If it is a callable, it will be called with the WSGI environ dict and should return a filename. Either way, the '.prof' extension will be appended to the name. The default format is '{method}.{path}.{elapsed:06d}ms.{time:d}'.

For the exact meaning of sort_by and restrictions consult the profile documentation.

New in version 0.9: Added support for restrictions and profile_dir.

New in version 0.15: Added profile_file_name_format.

Parameters:
  • app – the WSGI application to profile.
  • stream – the stream for the profiled stats. defaults to stderr.
  • sort_by – a tuple of columns to sort the result by.
  • restrictions – a tuple of profiling restrictions, not used if dumping to profile_dir.
  • profile_dir – directory name to save pstat files
  • filename_format – format of the filename excluding the extension.
werkzeug.contrib.profiler.make_action(app_factory, hostname='localhost', port=5000, threaded=False, processes=1, stream=None, sort_by=('time', 'calls'), restrictions=())

Return a new callback for werkzeug.script that starts a local server with the profiler enabled.

from werkzeug.contrib import profiler
action_profile = profiler.make_action(make_app)