Debian Codegraph @

src/flask_debugtoolbar/__init__.py

raw
1 from __future__ import annotations
2
3 import collections.abc as c
4 import os
5 import typing as t
6 import urllib.parse
7 import warnings
8 from contextvars import ContextVar
9
10 import jinja2.ext
11 from flask import Blueprint
12 from flask import current_app
13 from flask import Flask
14 from flask import g
15 from flask import request
16 from flask import send_from_directory
17 from flask import url_for
18 from flask.globals import request_ctx
19 from jinja2 import Environment
20 from jinja2 import PackageLoader
21 from werkzeug import Request
22 from werkzeug import Response
23 from werkzeug.routing import Rule
24
25 from .toolbar import DebugToolbar
26 from .utils import decode_text
27 from .utils import gzip_compress
28 from .utils import gzip_decompress
29
30 module: Blueprint = Blueprint("debugtoolbar", __name__)
31
32
33 def replace_insensitive(string: str, target: str, replacement: str) -> str:
34 """Similar to string.replace() but is case insensitive
35 Code borrowed from:
36 http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html
37 """
38 no_case = string.lower()
39 index = no_case.rfind(target.lower())
40
41 if index >= 0:
42 return string[:index] + replacement + string[index + len(target) :]
43 else: # no results so return the original string
44 return string
45
46
47 def _printable(value: object) -> str:
48 try:
49 return decode_text(repr(value))
50 except Exception as e:
51 return f"<repr({object.__repr__(value)}) raised {type(e).__name__}: {e}>"
52
53
54 class DebugToolbarExtension:
55 _static_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "static"))
56
57 _toolbar_codes = [200, 201, 400, 401, 403, 404, 405, 500, 501, 502, 503, 504]
58 _redirect_codes = [301, 302, 303, 304]
59
60 def __init__(self, app: Flask | None = None) -> None:
61 self.app = app
62 self.toolbar_routes_host: str | None = None
63
64 # Support threads running `flask.copy_current_request_context` without
65 # poping toolbar during `teardown_request`
66 self.debug_toolbars_var: ContextVar[dict[Request, DebugToolbar]] = ContextVar(
67 "debug_toolbars"
68 )
69 jinja_extensions = [jinja2.ext.i18n]
70
71 # Jinja2<3
72 if hasattr(jinja2.ext, "with_"):
73 jinja_extensions.append(jinja2.ext.with_) # pyright: ignore
74
75 # Configure jinja for the internal templates and add url rules
76 # for static data
77 self.jinja_env: Environment = Environment(
78 autoescape=True,
79 extensions=jinja_extensions,
80 loader=PackageLoader(__name__, "templates"),
81 )
82 self.jinja_env.filters["urlencode"] = urllib.parse.quote_plus
83 self.jinja_env.filters["printable"] = _printable
84 self.jinja_env.globals["url_for"] = url_for
85
86 if app is not None:
87 self.init_app(app)
88
89 def init_app(self, app: Flask) -> None:
90 for k, v in self._default_config(app).items():
91 app.config.setdefault(k, v)
92
93 if not app.config["DEBUG_TB_ENABLED"]:
94 return
95
96 if not app.config.get("SECRET_KEY"):
97 raise RuntimeError(
98 "The Flask-DebugToolbar requires the 'SECRET_KEY' config "
99 "var to be set"
100 )
101
102 self._validate_and_configure_toolbar_routes_host(app)
103
104 DebugToolbar.load_panels(app)
105
106 app.before_request(self.process_request)
107 app.after_request(self.process_response)
108 app.teardown_request(self.teardown_request)
109
110 # Monkey-patch the Flask.dispatch_request method
111 app.dispatch_request = self.dispatch_request # type: ignore[method-assign]
112
113 app.add_url_rule(
114 "/_debug_toolbar/static/<path:filename>",
115 "_debug_toolbar.static",
116 self.send_static_file,
117 host=self.toolbar_routes_host,
118 )
119
120 app.register_blueprint(module, url_prefix="/_debug_toolbar/views")
121
122 def _default_config(self, app: Flask) -> dict[str, t.Any]:
123 return {
124 "DEBUG_TB_ENABLED": app.debug,
125 "DEBUG_TB_HOSTS": (),
126 "DEBUG_TB_ROUTES_HOST": None,
127 "DEBUG_TB_INTERCEPT_REDIRECTS": True,
128 "DEBUG_TB_PANELS": (
129 "flask_debugtoolbar.panels.versions.VersionDebugPanel",
130 "flask_debugtoolbar.panels.timer.TimerDebugPanel",
131 "flask_debugtoolbar.panels.headers.HeaderDebugPanel",
132 "flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel",
133 "flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel",
134 "flask_debugtoolbar.panels.template.TemplateDebugPanel",
135 "flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel",
136 "flask_debugtoolbar.panels.logger.LoggingPanel",
137 "flask_debugtoolbar.panels.route_list.RouteListDebugPanel",
138 "flask_debugtoolbar.panels.profiler.ProfilerDebugPanel",
139 "flask_debugtoolbar.panels.g.GDebugPanel",
140 ),
141 "SQLALCHEMY_RECORD_QUERIES": app.debug,
142 }
143
144 def _validate_and_configure_toolbar_routes_host(self, app: Flask) -> None:
145 toolbar_routes_host = app.config["DEBUG_TB_ROUTES_HOST"]
146 if app.url_map.host_matching and not toolbar_routes_host:
147 import warnings
148
149 warnings.warn(
150 "Flask-DebugToolbar requires DEBUG_TB_ROUTES_HOST to be set if Flask "
151 "is running in `host_matching` mode. Static assets for the toolbar "
152 "will not be served correctly unless this is set.",
153 stacklevel=1,
154 )
155
156 if toolbar_routes_host:
157 if not app.url_map.host_matching:
158 raise ValueError(
159 "`DEBUG_TB_ROUTES_HOST` should only be set if your Flask app is "
160 "using `host_matching`."
161 )
162
163 if toolbar_routes_host.strip() == "*":
164 toolbar_routes_host = "<toolbar_routes_host>"
165 elif "<" in toolbar_routes_host and ">" in toolbar_routes_host:
166 raise ValueError(
167 "`DEBUG_TB_ROUTES_HOST` must either be a host name with no "
168 "variables, to serve all Flask-DebugToolbar assets from a single "
169 "host, or `*` to match the current request's host."
170 )
171
172 # Automatically inject `toolbar_routes_host` into `url_for` calls for
173 # the toolbar's `send_static_file` method.
174 @app.url_defaults
175 def inject_toolbar_routes_host_if_required(
176 endpoint: str, values: dict[str, t.Any]
177 ) -> None:
178 if app.url_map.is_endpoint_expecting(endpoint, "toolbar_routes_host"):
179 values.setdefault("toolbar_routes_host", request.host)
180
181 # Automatically strip `toolbar_routes_host` from the endpoint values so
182 # that the `send_static_host` method doesn't receive that parameter,
183 # as it's not actually required internally.
184 @app.url_value_preprocessor
185 def strip_toolbar_routes_host_from_static_endpoint(
186 endpoint: str | None, values: dict[str, t.Any] | None
187 ) -> None:
188 if (
189 endpoint
190 and values
191 and app.url_map.is_endpoint_expecting(
192 endpoint, "toolbar_routes_host"
193 )
194 ):
195 values.pop("toolbar_routes_host", None)
196
197 self.toolbar_routes_host = toolbar_routes_host
198
199 def dispatch_request(self) -> t.Any:
200 """Modified version of ``Flask.dispatch_request`` to call
201 :meth:`process_view`.
202 """
203 # self references this extension, use current_app to call app methods.
204 app = current_app._get_current_object() # type: ignore[attr-defined]
205 req = request_ctx.request
206
207 if req.routing_exception is not None:
208 app.raise_routing_exception(req)
209
210 rule: Rule = req.url_rule # type: ignore[assignment]
211
212 if (
213 getattr(rule, "provide_automatic_options", False)
214 and req.method == "OPTIONS"
215 ):
216 return app.make_default_options_response()
217
218 view_func = app.view_functions[rule.endpoint]
219 view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]
220 # allow each toolbar to process the view and args
221 view_func = self.process_view(app, view_func, view_args)
222 return view_func(**view_args)
223
224 def _show_toolbar(self) -> bool:
225 """Return a boolean to indicate if we need to show the toolbar."""
226 if request.blueprint == "debugtoolbar":
227 return False
228
229 hosts = current_app.config["DEBUG_TB_HOSTS"]
230
231 if hosts and request.remote_addr not in hosts:
232 return False
233
234 return True
235
236 def send_static_file(self, filename: str) -> Response:
237 """Send a static file from the flask-debugtoolbar static directory."""
238 return send_from_directory(self._static_dir, filename)
239
240 def process_request(self) -> None:
241 g.debug_toolbar = self
242
243 if not self._show_toolbar():
244 return
245
246 real_request = request._get_current_object() # type: ignore[attr-defined]
247 self.debug_toolbars_var.set({})
248 self.debug_toolbars_var.get()[real_request] = DebugToolbar(
249 real_request, self.jinja_env
250 )
251
252 for panel in self.debug_toolbars_var.get()[real_request].panels:
253 panel.process_request(real_request)
254
255 def process_view(
256 self,
257 app: Flask,
258 view_func: c.Callable[..., t.Any],
259 view_kwargs: dict[str, t.Any],
260 ) -> c.Callable[..., t.Any]:
261 """This method is called just before the flask view is called.
262 This is done by the dispatch_request method.
263 """
264 real_request = request._get_current_object() # type: ignore[attr-defined]
265
266 try:
267 toolbar = self.debug_toolbars_var.get({})[real_request]
268 except KeyError:
269 return view_func
270
271 for panel in toolbar.panels:
272 new_view = panel.process_view(real_request, view_func, view_kwargs)
273
274 if new_view:
275 view_func = new_view
276
277 return view_func
278
279 def process_response(self, response: Response) -> Response:
280 real_request = request._get_current_object() # type: ignore[attr-defined]
281
282 if real_request not in self.debug_toolbars_var.get({}):
283 return response
284
285 # Intercept http redirect codes and display an html page with a
286 # link to the target.
287 if current_app.config["DEBUG_TB_INTERCEPT_REDIRECTS"]:
288 if response.status_code in self._redirect_codes:
289 redirect_to = response.location
290 redirect_code = response.status_code
291
292 if redirect_to:
293 content = self.render(
294 "redirect.html",
295 {"redirect_to": redirect_to, "redirect_code": redirect_code},
296 )
297 response.content_length = len(content)
298 del response.location
299 response.response = [content]
300 response.status_code = 200
301
302 # If the http response code is an allowed code then we process to add the
303 # toolbar to the returned html response.
304 if not (
305 response.status_code in self._toolbar_codes
306 and response.is_sequence
307 and response.headers["content-type"].startswith("text/html")
308 ):
309 return response
310
311 content_encoding = response.headers.get("Content-Encoding")
312
313 if content_encoding and "gzip" in content_encoding:
314 response_html = gzip_decompress(response.data).decode()
315 else:
316 response_html = response.get_data(as_text=True)
317
318 no_case = response_html.lower()
319 body_end = no_case.rfind("</body>")
320
321 if body_end >= 0:
322 before = response_html[:body_end]
323 after = response_html[body_end:]
324 elif no_case.startswith("<!doctype html>"):
325 before = response_html
326 after = ""
327 else:
328 warnings.warn(
329 "Could not insert debug toolbar." " </body> tag not found in response.",
330 stacklevel=1,
331 )
332 return response
333
334 toolbar = self.debug_toolbars_var.get()[real_request]
335
336 for panel in toolbar.panels:
337 panel.process_response(real_request, response)
338
339 toolbar_html = toolbar.render_toolbar()
340
341 content = "".join((before, toolbar_html, after))
342 content_bytes = content.encode("utf-8")
343
344 if content_encoding and "gzip" in content_encoding:
345 content_bytes = gzip_compress(content_bytes)
346
347 response.response = [content_bytes]
348 response.content_length = len(content_bytes)
349
350 return response
351
352 def teardown_request(self, exc: BaseException | None) -> None:
353 # debug_toolbars_var won't be set under `flask.copy_current_request_context`
354 real_request = request._get_current_object() # type: ignore[attr-defined]
355 self.debug_toolbars_var.get({}).pop(real_request, None)
356
357 def render(self, template_name: str, context: dict[str, t.Any]) -> str:
358 template = self.jinja_env.get_template(template_name)
359 return template.render(**context)