Debian Codegraph @

src/flask_debugtoolbar/panels/profiler.py

raw
1 from __future__ import annotations
2
3 import collections.abc as c
4 import functools
5 import pstats
6 import typing as t
7
8 from flask import current_app
9 from jinja2 import Environment
10 from werkzeug import Request
11 from werkzeug import Response
12
13 from ..utils import format_fname
14 from . import DebugPanel
15
16 try:
17 import cProfile as profile
18 except ImportError:
19 import profile # type: ignore[no-redef]
20
21
22 class ProfilerDebugPanel(DebugPanel):
23 """Panel that displays the time a response took with cProfile output."""
24
25 name = "Profiler"
26 user_activate = True
27
28 is_active: bool = False
29 dump_filename: str | None = None
30 profiler: profile.Profile
31 stats: pstats.Stats | None = None
32 function_calls: list[dict[str, t.Any]]
33
34 def __init__(
35 self, jinja_env: Environment, context: dict[str, t.Any] | None = None
36 ) -> None:
37 super().__init__(jinja_env, context=context)
38
39 if current_app.config.get("DEBUG_TB_PROFILER_ENABLED"):
40 self.is_active = True
41 self.dump_filename = current_app.config.get(
42 "DEBUG_TB_PROFILER_DUMP_FILENAME"
43 )
44
45 @property
46 def has_content(self) -> bool: # type: ignore[override]
47 return bool(self.profiler)
48
49 def process_request(self, request: Request) -> None:
50 if not self.is_active:
51 return
52
53 self.profiler = profile.Profile() # pyright: ignore
54 self.stats = None
55
56 def process_view(
57 self,
58 request: Request,
59 view_func: c.Callable[..., t.Any],
60 view_kwargs: dict[str, t.Any],
61 ) -> c.Callable[..., t.Any] | None:
62 if self.is_active:
63 func = functools.partial(self.profiler.runcall, view_func)
64 functools.update_wrapper(func, view_func)
65 return func
66
67 return None
68
69 def process_response(self, request: Request, response: Response) -> None:
70 if not self.is_active:
71 return
72
73 if self.profiler is not None:
74 self.profiler.disable() # pyright: ignore
75
76 try:
77 stats = pstats.Stats(self.profiler)
78 except TypeError:
79 self.is_active = False
80 return
81
82 function_calls: list[dict[str, t.Any]] = []
83
84 for func in stats.sort_stats(1).fcn_list: # type: ignore[attr-defined]
85 current: dict[str, t.Any] = {}
86 info = stats.stats[func] # type: ignore[attr-defined]
87
88 # Number of calls
89 if info[0] != info[1]:
90 current["ncalls"] = f"{info[1]}/{info[0]}"
91 else:
92 current["ncalls"] = info[1]
93
94 # Total time
95 current["tottime"] = info[2] * 1000
96
97 # Quotient of total time divided by number of calls
98 if info[1]:
99 current["percall"] = info[2] * 1000 / info[1]
100 else:
101 current["percall"] = 0
102
103 # Cumulative time
104 current["cumtime"] = info[3] * 1000
105
106 # Quotient of the cumulative time divided by the number of
107 # primitive calls.
108 if info[0]:
109 current["percall_cum"] = info[3] * 1000 / info[0]
110 else:
111 current["percall_cum"] = 0
112
113 # Filename
114 filename = pstats.func_std_string(func) # type: ignore[attr-defined]
115 current["filename_long"] = filename
116 current["filename"] = format_fname(filename)
117 function_calls.append(current)
118
119 self.stats = stats
120 self.function_calls = function_calls
121
122 if self.dump_filename:
123 if callable(self.dump_filename):
124 filename = self.dump_filename()
125 else:
126 filename = self.dump_filename
127
128 self.profiler.dump_stats(filename)
129
130 def title(self) -> str:
131 if not self.is_active:
132 return "Profiler not active"
133
134 return f"View: {float(self.stats.total_tt) * 1000:.2f}ms" # type: ignore[union-attr]
135
136 def nav_title(self) -> str:
137 return "Profiler"
138
139 def nav_subtitle(self) -> str:
140 if not self.is_active:
141 return "in-active"
142
143 return f"View: {float(self.stats.total_tt) * 1000:.2f}ms" # type: ignore[union-attr]
144
145 def url(self) -> str:
146 return ""
147
148 def content(self) -> str:
149 if not self.is_active:
150 return "The profiler is not activated, activate it to use it"
151
152 context = {
153 "stats": self.stats,
154 "function_calls": self.function_calls,
155 }
156 return self.render("panels/profiler.html", context)