From cd9f0b41115f82ff7a64f5a63bc6222a6c51594e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= Date: Tue, 12 May 2026 08:10:33 +0200 Subject: [PATCH] Caching 1/? --- common/components.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/common/components.py b/common/components.py index a8e2ec1..c895a5d 100644 --- a/common/components.py +++ b/common/components.py @@ -1,7 +1,10 @@ +import json +from functools import lru_cache from random import choices as random_choices from string import ascii_lowercase from typing import Any, Callable +from django.conf import settings from django.template import TemplateDoesNotExist from django.template.defaultfilters import floatformat from django.template.loader import render_to_string @@ -15,6 +18,16 @@ HTMLAttribute = tuple[str, str | int | bool] 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( attributes: list[HTMLAttribute] = [], children: list[HTMLTag] | HTMLTag = [], @@ -37,11 +50,8 @@ def Component( if tag_name != "": tag = f"<{tag_name}{attributesBlob}>{childrenBlob}" elif template != "": - tag = render_to_string( - template, - {name: value for name, value in attributes} - | {"slot": mark_safe("\n".join(children))}, - ) + context = {name: value for name, value in attributes} | {"slot": "\n".join(children)} + tag = _render_cached(template, json.dumps(context, sort_keys=True)) return mark_safe(tag)