You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cached.py 3.5KB

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