Caching 1/?

This commit is contained in:
2026-05-12 08:10:33 +02:00
parent f82c61ef1e
commit cd9f0b4111
+15 -5
View File
@@ -1,7 +1,10 @@
import json
from functools import lru_cache
from random import choices as random_choices from random import choices as random_choices
from string import ascii_lowercase from string import ascii_lowercase
from typing import Any, Callable from typing import Any, Callable
from django.conf import settings
from django.template import TemplateDoesNotExist from django.template import TemplateDoesNotExist
from django.template.defaultfilters import floatformat from django.template.defaultfilters import floatformat
from django.template.loader import render_to_string from django.template.loader import render_to_string
@@ -15,6 +18,16 @@ HTMLAttribute = tuple[str, str | int | bool]
HTMLTag = str HTMLTag = str
def _render_cached(template: str, context_json: str) -> str:
context = json.loads(context_json)
context["slot"] = mark_safe(context["slot"])
return render_to_string(template, context)
if not settings.DEBUG:
_render_cached = lru_cache(maxsize=4096)(_render_cached)
def Component( def Component(
attributes: list[HTMLAttribute] = [], attributes: list[HTMLAttribute] = [],
children: list[HTMLTag] | HTMLTag = [], children: list[HTMLTag] | HTMLTag = [],
@@ -37,11 +50,8 @@ def Component(
if tag_name != "": if tag_name != "":
tag = f"<{tag_name}{attributesBlob}>{childrenBlob}</{tag_name}>" tag = f"<{tag_name}{attributesBlob}>{childrenBlob}</{tag_name}>"
elif template != "": elif template != "":
tag = render_to_string( context = {name: value for name, value in attributes} | {"slot": "\n".join(children)}
template, tag = _render_cached(template, json.dumps(context, sort_keys=True))
{name: value for name, value in attributes}
| {"slot": mark_safe("\n".join(children))},
)
return mark_safe(tag) return mark_safe(tag)