Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/template/backends/django.py: 73%
75 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from importlib import import_module
2from pkgutil import walk_packages
4from django.apps import apps
5from django.conf import settings
6from django.template import TemplateDoesNotExist
7from django.template.context import make_context
8from django.template.engine import Engine
9from django.template.library import InvalidTemplateLibrary
11from .base import BaseEngine
14class DjangoTemplates(BaseEngine):
16 app_dirname = "templates"
18 def __init__(self, params):
19 params = params.copy()
20 options = params.pop("OPTIONS").copy()
21 options.setdefault("autoescape", True)
22 options.setdefault("debug", settings.DEBUG)
23 options.setdefault("file_charset", "utf-8")
24 libraries = options.get("libraries", {})
25 options["libraries"] = self.get_templatetag_libraries(libraries)
26 super().__init__(params)
27 self.engine = Engine(self.dirs, self.app_dirs, **options)
29 def from_string(self, template_code):
30 return Template(self.engine.from_string(template_code), self)
32 def get_template(self, template_name):
33 try:
34 return Template(self.engine.get_template(template_name), self)
35 except TemplateDoesNotExist as exc:
36 reraise(exc, self)
38 def get_templatetag_libraries(self, custom_libraries):
39 """
40 Return a collation of template tag libraries from installed
41 applications and the supplied custom_libraries argument.
42 """
43 libraries = get_installed_libraries()
44 libraries.update(custom_libraries)
45 return libraries
48class Template:
49 def __init__(self, template, backend):
50 self.template = template
51 self.backend = backend
53 @property
54 def origin(self):
55 return self.template.origin
57 def render(self, context=None, request=None):
58 context = make_context(
59 context, request, autoescape=self.backend.engine.autoescape
60 )
61 try:
62 return self.template.render(context)
63 except TemplateDoesNotExist as exc:
64 reraise(exc, self.backend)
67def copy_exception(exc, backend=None):
68 """
69 Create a new TemplateDoesNotExist. Preserve its declared attributes and
70 template debug data but discard __traceback__, __context__, and __cause__
71 to make this object suitable for keeping around (in a cache, for example).
72 """
73 backend = backend or exc.backend
74 new = exc.__class__(*exc.args, tried=exc.tried, backend=backend, chain=exc.chain)
75 if hasattr(exc, "template_debug"):
76 new.template_debug = exc.template_debug
77 return new
80def reraise(exc, backend):
81 """
82 Reraise TemplateDoesNotExist while maintaining template debug information.
83 """
84 new = copy_exception(exc, backend)
85 raise new from exc
88def get_installed_libraries():
89 """
90 Return the built-in template tag libraries and those from installed
91 applications. Libraries are stored in a dictionary where keys are the
92 individual module names, not the full module paths. Example:
93 django.templatetags.i18n is stored as i18n.
94 """
95 libraries = {}
96 candidates = ["django.templatetags"]
97 candidates.extend(
98 "%s.templatetags" % app_config.name for app_config in apps.get_app_configs()
99 )
101 for candidate in candidates:
102 try:
103 pkg = import_module(candidate)
104 except ImportError:
105 # No templatetags package defined. This is safe to ignore.
106 continue
108 if hasattr(pkg, "__path__"): 108 ↛ 101line 108 didn't jump to line 101, because the condition on line 108 was never false
109 for name in get_package_libraries(pkg):
110 libraries[name[len(candidate) + 1 :]] = name
112 return libraries
115def get_package_libraries(pkg):
116 """
117 Recursively yield template tag libraries defined in submodules of a
118 package.
119 """
120 for entry in walk_packages(pkg.__path__, pkg.__name__ + "."):
121 try:
122 module = import_module(entry[1])
123 except ImportError as e:
124 raise InvalidTemplateLibrary(
125 "Invalid template library specified. ImportError raised when "
126 "trying to load '%s': %s" % (entry[1], e)
127 ) from e
129 if hasattr(module, "register"):
130 yield entry[1]