diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 4ca442c54..ed8ed227c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -5,6 +5,9 @@ Change history for XBlock Unreleased ---------- +* ``ResourceLoader.render_django_template`` (and ``render_js_template``) now build their template + engine once per process instead of on every call. Each call used to scan every installed app for + template tag libraries, which took about 3 ms per render in openedx-platform. * Fixed ``webob_to_django_response`` dropping all but the last ``Set-Cookie`` header; they are now loaded into the Django response's cookie jar so every cookie is sent to the client. diff --git a/xblock/test/utils/test_resources.py b/xblock/test/utils/test_resources.py index 1ddd59ede..b9bda72be 100644 --- a/xblock/test/utils/test_resources.py +++ b/xblock/test/utils/test_resources.py @@ -9,6 +9,7 @@ import importlib.resources +from xblock.utils import resources from xblock.utils.resources import ResourceLoader expected_string = """\ @@ -185,6 +186,35 @@ def test_render_django_template_localized(self): i18n_service=MockI18nService()) self.assertEqual(s, expected_localized_template) + def test_render_django_template_reuses_engine(self): + # Building the engine scans every installed app for template tag libraries, so it must + # happen once, not once per render. + resources._get_django_template_engine.cache_clear() # pylint: disable=protected-access + loader = ResourceLoader(__name__) + with patch.object( + resources, "get_installed_libraries", wraps=resources.get_installed_libraries + ) as mock_get_installed_libraries: + for _ in range(3): + s = loader.render_django_template("data/simple_django_template.txt", dict(example_context)) + self.assertEqual(s, expected_filled_template) + ResourceLoader("xblock.test.utils.data").render_django_template("simple_django_template.txt") + self.assertEqual(mock_get_installed_libraries.call_count, 1) + + def test_django_template_engine_follows_installed_apps(self): + # The tag libraries come from the installed apps, so a changed INSTALLED_APPS needs a new engine. + # The receiver is called directly: override_settings(INSTALLED_APPS=...) would also reset + # Django's translations, which the translation tests in this class are sensitive to. + get_engine = resources._get_django_template_engine # pylint: disable=protected-access + reset_engine = resources._reset_django_template_engine # pylint: disable=protected-access + engine = get_engine() + self.assertIs(get_engine(), engine) + + reset_engine(setting="DEBUG") + self.assertIs(get_engine(), engine) + + reset_engine(setting="INSTALLED_APPS") + self.assertIsNot(get_engine(), engine) + def test_render_mako_template(self): loader = ResourceLoader(__name__) s = loader.render_mako_template("data/simple_mako_template.txt", example_context) diff --git a/xblock/utils/resources.py b/xblock/utils/resources.py index f3f2ac69f..8a5519898 100644 --- a/xblock/utils/resources.py +++ b/xblock/utils/resources.py @@ -1,17 +1,48 @@ """ Helper class (ResourceLoader) for loading resources used by an XBlock """ +import functools import os import sys import warnings import importlib.resources +from django.core.signals import setting_changed +from django.dispatch import receiver from django.template import Context, Engine, Template from django.template.backends.django import get_installed_libraries from mako.lookup import TemplateLookup as MakoTemplateLookup from mako.template import Template as MakoTemplate +@functools.cache +def _get_django_template_engine(): + """ + Return the template engine that ``ResourceLoader.render_django_template`` renders with. + + It knows every installed template tag library, except that ``{% load i18n %}`` loads XBlock's + own ``trans`` and ``blocktrans`` tags, which translate through the block's i18n service. + + The engine is built once per process. Finding the installed libraries means scanning the + ``templatetags`` package of every installed app, which is too slow to repeat on every render. + The engine is not changed by rendering, so sharing it between calls and threads is safe. + """ + libraries = get_installed_libraries() + libraries['i18n'] = 'xblock.utils.templatetags.i18n' + return Engine(libraries=libraries) + + +@receiver(setting_changed) +def _reset_django_template_engine(*, setting, **kwargs): + """ + Rebuild the engine when the set of installed apps, and so of tag libraries, changes. + + Settings only change at runtime in tests, through ``override_settings``. + """ + if setting == 'INSTALLED_APPS': + _get_django_template_engine.cache_clear() + + class ResourceLoader: """Loads resources relative to the module named by the module_name parameter.""" def __init__(self, module_name): @@ -35,16 +66,9 @@ def render_django_template(self, template_path, context=None, i18n_service=None) """ context = context or {} context['_i18n_service'] = i18n_service - libraries = { - 'i18n': 'xblock.utils.templatetags.i18n', - } - - installed_libraries = get_installed_libraries() - installed_libraries.update(libraries) - engine = Engine(libraries=installed_libraries) template_str = self.load_unicode(template_path) - template = Template(template_str, engine=engine) + template = Template(template_str, engine=_get_django_template_engine()) rendered = template.render(Context(context)) return rendered