profiler.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """
  2. Application Profiler
  3. ====================
  4. This module provides a middleware that profiles each request with the
  5. :mod:`cProfile` module. This can help identify bottlenecks in your code
  6. that may be slowing down your application.
  7. .. autoclass:: ProfilerMiddleware
  8. :copyright: 2007 Pallets
  9. :license: BSD-3-Clause
  10. """
  11. from __future__ import annotations
  12. import os.path
  13. import sys
  14. import time
  15. import typing as t
  16. from pstats import Stats
  17. if sys.version_info >= (3, 15):
  18. from profiling.tracing import Profile
  19. else:
  20. try:
  21. from cProfile import Profile
  22. except ImportError:
  23. from profile import Profile # type: ignore[assignment]
  24. if t.TYPE_CHECKING:
  25. from _typeshed.wsgi import StartResponse
  26. from _typeshed.wsgi import WSGIApplication
  27. from _typeshed.wsgi import WSGIEnvironment
  28. class ProfilerMiddleware:
  29. """Wrap a WSGI application and profile the execution of each
  30. request. Responses are buffered so that timings are more exact.
  31. If ``stream`` is given, :class:`pstats.Stats` are written to it
  32. after each request. If ``profile_dir`` is given, :mod:`cProfile`
  33. data files are saved to that directory, one file per request.
  34. The filename can be customized by passing ``filename_format``. If
  35. it is a string, it will be formatted using :meth:`str.format` with
  36. the following fields available:
  37. - ``{method}`` - The request method; GET, POST, etc.
  38. - ``{path}`` - The request path or 'root' should one not exist.
  39. - ``{elapsed}`` - The elapsed time of the request in milliseconds.
  40. - ``{time}`` - The time of the request.
  41. If it is a callable, it will be called with the WSGI ``environ`` and
  42. be expected to return a filename string. The ``environ`` dictionary
  43. will also have the ``"werkzeug.profiler"`` key populated with a
  44. dictionary containing the following fields (more may be added in the
  45. future):
  46. - ``{elapsed}`` - The elapsed time of the request in milliseconds.
  47. - ``{time}`` - The time of the request.
  48. :param app: The WSGI application to wrap.
  49. :param stream: Write stats to this stream. Disable with ``None``.
  50. :param sort_by: A tuple of columns to sort stats by. See
  51. :meth:`pstats.Stats.sort_stats`.
  52. :param restrictions: A tuple of restrictions to filter stats by. See
  53. :meth:`pstats.Stats.print_stats`.
  54. :param profile_dir: Save profile data files to this directory.
  55. :param filename_format: Format string for profile data file names,
  56. or a callable returning a name. See explanation above.
  57. .. code-block:: python
  58. from werkzeug.middleware.profiler import ProfilerMiddleware
  59. app = ProfilerMiddleware(app)
  60. .. versionchanged:: 3.0
  61. Added the ``"werkzeug.profiler"`` key to the ``filename_format(environ)``
  62. parameter with the ``elapsed`` and ``time`` fields.
  63. .. versionchanged:: 0.15
  64. Stats are written even if ``profile_dir`` is given, and can be
  65. disable by passing ``stream=None``.
  66. .. versionadded:: 0.15
  67. Added ``filename_format``.
  68. .. versionadded:: 0.9
  69. Added ``restrictions`` and ``profile_dir``.
  70. """
  71. def __init__(
  72. self,
  73. app: WSGIApplication,
  74. stream: t.IO[str] | None = sys.stdout,
  75. sort_by: t.Iterable[str] = ("time", "calls"),
  76. restrictions: t.Iterable[str | int | float] = (),
  77. profile_dir: str | None = None,
  78. filename_format: str = "{method}.{path}.{elapsed:.0f}ms.{time:.0f}.prof",
  79. ) -> None:
  80. self._app = app
  81. self._stream = stream
  82. self._sort_by = sort_by
  83. self._restrictions = restrictions
  84. self._profile_dir = profile_dir
  85. self._filename_format = filename_format
  86. def __call__(
  87. self, environ: WSGIEnvironment, start_response: StartResponse
  88. ) -> t.Iterable[bytes]:
  89. response_body: list[bytes] = []
  90. def catching_start_response(status, headers, exc_info=None): # type: ignore
  91. start_response(status, headers, exc_info)
  92. return response_body.append
  93. def runapp() -> None:
  94. app_iter = self._app(
  95. environ, t.cast("StartResponse", catching_start_response)
  96. )
  97. response_body.extend(app_iter)
  98. if hasattr(app_iter, "close"):
  99. app_iter.close()
  100. profile = Profile()
  101. start = time.time()
  102. profile.runcall(runapp)
  103. body = b"".join(response_body)
  104. elapsed = time.time() - start
  105. if self._profile_dir is not None:
  106. if callable(self._filename_format):
  107. environ["werkzeug.profiler"] = {
  108. "elapsed": elapsed * 1000.0,
  109. "time": time.time(),
  110. }
  111. filename = self._filename_format(environ)
  112. else:
  113. filename = self._filename_format.format(
  114. method=environ["REQUEST_METHOD"],
  115. path=environ["PATH_INFO"].strip("/").replace("/", ".") or "root",
  116. elapsed=elapsed * 1000.0,
  117. time=time.time(),
  118. )
  119. filename = os.path.join(self._profile_dir, filename)
  120. profile.dump_stats(filename)
  121. if self._stream is not None:
  122. stats = Stats(profile, stream=self._stream)
  123. stats.sort_stats(*self._sort_by)
  124. print("-" * 80, file=self._stream)
  125. path_info = environ.get("PATH_INFO", "")
  126. print(f"PATH: {path_info!r}", file=self._stream)
  127. stats.print_stats(*self._restrictions)
  128. print(f"{'-' * 80}\n", file=self._stream)
  129. return [body]