From d57985dca1968fcc4f7f6d73a87ab3a5a4bbe142 Mon Sep 17 00:00:00 2001 From: Tim Schilling Date: Mon, 19 Feb 2024 07:26:52 -0600 Subject: [PATCH] WIP: instrument the jinja render function (more) It instruments the single template render, but not the inherited templates and I'm guessing not the included templates either. I suspect we're going to have to patch jinja templates more robustly than relying on the django jinja backend template class. --- debug_toolbar/panels/templates/jinja2.py | 22 ++++++++++++++++++++++ debug_toolbar/panels/templates/panel.py | 2 ++ 2 files changed, 24 insertions(+) create mode 100644 debug_toolbar/panels/templates/jinja2.py diff --git a/debug_toolbar/panels/templates/jinja2.py b/debug_toolbar/panels/templates/jinja2.py new file mode 100644 index 000000000..8d85b8f57 --- /dev/null +++ b/debug_toolbar/panels/templates/jinja2.py @@ -0,0 +1,22 @@ +import functools + +from django.template.backends.jinja2 import Template as JinjaTemplate +from django.template.context import make_context +from django.test.signals import template_rendered + + +def patch_jinja_render(): + orig_render = JinjaTemplate.render + + @functools.wraps(orig_render) + def wrapped_render(self, context=None, request=None): + print(self.template.name) + self.name = self.template.name + template_rendered.send( + sender=self, template=self, context=make_context(context, request) + ) + return orig_render(self, context, request) + + if JinjaTemplate.render != wrapped_render: + JinjaTemplate.original_render = JinjaTemplate.render + JinjaTemplate.render = wrapped_render diff --git a/debug_toolbar/panels/templates/panel.py b/debug_toolbar/panels/templates/panel.py index 81d7e5fad..182f80aab 100644 --- a/debug_toolbar/panels/templates/panel.py +++ b/debug_toolbar/panels/templates/panel.py @@ -14,6 +14,7 @@ from debug_toolbar.panels import Panel from debug_toolbar.panels.sql.tracking import SQLQueryTriggered, allow_sql from debug_toolbar.panels.templates import views +from debug_toolbar.panels.templates.jinja2 import patch_jinja_render # Monkey-patch to enable the template_rendered signal. The receiver returns # immediately when the panel is disabled to keep the overhead small. @@ -25,6 +26,7 @@ Template.original_render = Template._render Template._render = instrumented_test_render +patch_jinja_render() # Monkey-patch to store items added by template context processors. The # overhead is sufficiently small to justify enabling it unconditionally.