cached.py 3.4 KB

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