| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import sys |
| 5 |
import typing as t |
| 6 |
import uuid |
| 7 |
from collections import deque |
| 8 |
|
| 9 |
from flask import abort |
| 10 |
from flask import current_app |
| 11 |
from flask import g |
| 12 |
from flask import request |
| 13 |
from flask import Response |
| 14 |
from flask import template_rendered |
| 15 |
from flask import url_for |
| 16 |
from jinja2 import Template |
| 17 |
|
| 18 |
from .. import module |
| 19 |
from . import DebugPanel |
| 20 |
|
| 21 |
|
| 22 |
class TemplateDebugPanel(DebugPanel): |
| 23 |
"""Panel that displays the time a response took in milliseconds.""" |
| 24 |
|
| 25 |
name = "Template" |
| 26 |
has_content = True |
| 27 |
|
| 28 |
# save the context for the 5 most recent requests |
| 29 |
template_cache: deque[tuple[str, list[dict[str, t.Any]]]] = deque(maxlen=5) |
| 30 |
|
| 31 |
@classmethod |
| 32 |
def get_cache_for_key(cls, key: str) -> list[dict[str, t.Any]]: |
| 33 |
for cache_key, value in cls.template_cache: |
| 34 |
if key == cache_key: |
| 35 |
return value |
| 36 |
|
| 37 |
raise KeyError(key) |
| 38 |
|
| 39 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: |
| 40 |
super().__init__(*args, **kwargs) |
| 41 |
self.key: str = str(uuid.uuid4()) |
| 42 |
self.templates: list[dict[str, t.Any]] = [] |
| 43 |
template_rendered.connect(self._store_template_info) |
| 44 |
|
| 45 |
def _store_template_info(self, sender: t.Any, **kwargs: t.Any) -> None: |
| 46 |
# only record in the cache if the editor is enabled and there is |
| 47 |
# actually a template for this request |
| 48 |
if not self.templates and is_editor_enabled(): |
| 49 |
self.template_cache.append((self.key, self.templates)) |
| 50 |
|
| 51 |
self.templates.append(kwargs) |
| 52 |
|
| 53 |
def nav_title(self) -> str: |
| 54 |
return "Templates" |
| 55 |
|
| 56 |
def nav_subtitle(self) -> str: |
| 57 |
return f"{len(self.templates)} rendered" |
| 58 |
|
| 59 |
def title(self) -> str: |
| 60 |
return "Templates" |
| 61 |
|
| 62 |
def url(self) -> str: |
| 63 |
return "" |
| 64 |
|
| 65 |
def content(self) -> str: |
| 66 |
return self.render( |
| 67 |
"panels/template.html", |
| 68 |
{ |
| 69 |
"key": self.key, |
| 70 |
"templates": self.templates, |
| 71 |
"editable": is_editor_enabled(), |
| 72 |
}, |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
def is_editor_enabled() -> bool: |
| 77 |
return current_app.config.get("DEBUG_TB_TEMPLATE_EDITOR_ENABLED", False) # type: ignore |
| 78 |
|
| 79 |
|
| 80 |
def require_enabled() -> None: |
| 81 |
if not is_editor_enabled(): |
| 82 |
abort(403) |
| 83 |
|
| 84 |
|
| 85 |
def _get_source(template: Template) -> str: |
| 86 |
if template.filename is None: |
| 87 |
return "" |
| 88 |
|
| 89 |
with open(template.filename, "rb") as fp: |
| 90 |
source = fp.read() |
| 91 |
|
| 92 |
return source.decode(_template_encoding()) |
| 93 |
|
| 94 |
|
| 95 |
def _template_encoding() -> str: |
| 96 |
return getattr(current_app.jinja_loader, "encoding", "utf-8") |
| 97 |
|
| 98 |
|
| 99 |
@module.route("/template/<key>") |
| 100 |
def template_editor(key: str) -> str: |
| 101 |
require_enabled() |
| 102 |
# TODO set up special loader that caches templates it loads |
| 103 |
# and can override template contents |
| 104 |
templates = [t["template"] for t in TemplateDebugPanel.get_cache_for_key(key)] |
| 105 |
return g.debug_toolbar.render( # type: ignore[no-any-return] |
| 106 |
"panels/template_editor.html", |
| 107 |
{ |
| 108 |
"static_path": url_for("_debug_toolbar.static", filename=""), |
| 109 |
"request": request, |
| 110 |
"templates": [ |
| 111 |
{"name": t.name, "source": _get_source(t)} for t in templates |
| 112 |
], |
| 113 |
}, |
| 114 |
) |
| 115 |
|
| 116 |
|
| 117 |
@module.route("/template/<key>/save", methods=["POST"]) |
| 118 |
def save_template(key: str) -> str: |
| 119 |
require_enabled() |
| 120 |
template = TemplateDebugPanel.get_cache_for_key(key)[0]["template"] |
| 121 |
content = request.form["content"].encode(_template_encoding()) |
| 122 |
|
| 123 |
with open(template.filename, "wb") as fp: |
| 124 |
fp.write(content) |
| 125 |
|
| 126 |
return "ok" |
| 127 |
|
| 128 |
|
| 129 |
@module.route("/template/<key>", methods=["POST"]) |
| 130 |
def template_preview(key: str) -> str | Response: |
| 131 |
require_enabled() |
| 132 |
context = TemplateDebugPanel.get_cache_for_key(key)[0]["context"] |
| 133 |
content = request.form["content"] |
| 134 |
env = current_app.jinja_env.overlay(autoescape=True) |
| 135 |
|
| 136 |
try: |
| 137 |
template = env.from_string(content) |
| 138 |
return template.render(context) |
| 139 |
except Exception as e: |
| 140 |
tb = sys.exc_info()[2] |
| 141 |
|
| 142 |
try: |
| 143 |
while tb.tb_next: # type: ignore[union-attr] |
| 144 |
tb = tb.tb_next # type: ignore[union-attr] |
| 145 |
|
| 146 |
msg = {"lineno": tb.tb_lineno, "error": str(e)} # type: ignore[union-attr] |
| 147 |
return Response(json.dumps(msg), status=400, mimetype="application/json") |
| 148 |
finally: |
| 149 |
del tb |