Debian Codegraph @

django/template/loaders/cached.py

raw
1 """
2 Wrapper class that takes a list of template loaders as an argument and attempts
3 to load templates from them in order, caching the result.
4 """
5
6 import hashlib
7
8 from django.template import TemplateDoesNotExist
9 from django.template.backends.django import copy_exception
10
11 from .base import Loader as BaseLoader
12
13
14 class Loader(BaseLoader):
15 def __init__(self, engine, loaders):
16 self.get_template_cache = {}
17 self.loaders = engine.get_template_loaders(loaders)
18 super().__init__(engine)
19
20 def get_dirs(self):
21 for loader in self.loaders:
22 if hasattr(loader, "get_dirs"):
23 yield from loader.get_dirs()
24
25 def get_contents(self, origin):
26 return origin.loader.get_contents(origin)
27
28 def get_template(self, template_name, skip=None):
29 """
30 Perform the caching that gives this loader its name. Often many of the
31 templates attempted will be missing, so memory use is of concern here.
32 To keep it in check, caching behavior is a little complicated when a
33 template is not found. See ticket #26306 for more details.
34
35 With template debugging disabled, cache the TemplateDoesNotExist class
36 for every missing template and raise a new instance of it after
37 fetching it from the cache.
38
39 With template debugging enabled, a unique TemplateDoesNotExist object
40 is cached for each missing template to preserve debug data. When
41 raising an exception, Python sets __traceback__, __context__, and
42 __cause__ attributes on it. Those attributes can contain references to
43 all sorts of objects up the call chain and caching them creates a
44 memory leak. Thus, unraised copies of the exceptions are cached and
45 copies of those copies are raised after they're fetched from the cache.
46 """
47 key = self.cache_key(template_name, skip)
48 cached = self.get_template_cache.get(key)
49 if cached:
50 if isinstance(cached, type) and issubclass(cached, TemplateDoesNotExist):
51 raise cached(template_name)
52 elif isinstance(cached, TemplateDoesNotExist):
53 raise copy_exception(cached)
54 return cached
55
56 try:
57 template = super().get_template(template_name, skip)
58 except TemplateDoesNotExist as e:
59 self.get_template_cache[key] = (
60 copy_exception(e) if self.engine.debug else TemplateDoesNotExist
61 )
62 raise
63 else:
64 self.get_template_cache[key] = template
65
66 return template
67
68 def get_template_sources(self, template_name):
69 for loader in self.loaders:
70 yield from loader.get_template_sources(template_name)
71
72 def cache_key(self, template_name, skip=None):
73 """
74 Generate a cache key for the template name and skip.
75
76 If skip is provided, only origins that match template_name are included
77 in the cache key. This ensures each template is only parsed and cached
78 once if contained in different extend chains like:
79
80 x -> a -> a
81 y -> a -> a
82 z -> a -> a
83 """
84 skip_prefix = ""
85
86 if skip:
87 matching = [
88 origin.name for origin in skip if origin.template_name == template_name
89 ]
90 if matching:
91 skip_prefix = self.generate_hash(matching)
92
93 return "-".join(s for s in (str(template_name), skip_prefix) if s)
94
95 def generate_hash(self, values):
96 return hashlib.sha1("|".join(values).encode()).hexdigest()
97
98 def reset(self):
99 "Empty the template cache."
100 self.get_template_cache.clear()