Debian Codegraph @

django/template/loaders/filesystem.py

raw
1 """
2 Wrapper for loading templates from the filesystem.
3 """
4
5 from django.core.exceptions import SuspiciousFileOperation
6 from django.template import Origin, TemplateDoesNotExist
7 from django.utils._os import safe_join
8
9 from .base import Loader as BaseLoader
10
11
12 class Loader(BaseLoader):
13 def __init__(self, engine, dirs=None):
14 super().__init__(engine)
15 self.dirs = dirs
16
17 def get_dirs(self):
18 return self.dirs if self.dirs is not None else self.engine.dirs
19
20 def get_contents(self, origin):
21 try:
22 with open(origin.name, encoding=self.engine.file_charset) as fp:
23 return fp.read()
24 except FileNotFoundError:
25 raise TemplateDoesNotExist(origin)
26
27 def get_template_sources(self, template_name):
28 """
29 Return an Origin object pointing to an absolute path in each directory
30 in template_dirs. For security reasons, if a path doesn't lie inside
31 one of the template_dirs it is excluded from the result set.
32 """
33 for template_dir in self.get_dirs():
34 try:
35 name = safe_join(template_dir, template_name)
36 except SuspiciousFileOperation:
37 # The joined path was located outside of this template_dir
38 # (it might be inside another one, so this isn't fatal).
39 continue
40
41 yield Origin(
42 name=name,
43 template_name=template_name,
44 loader=self,
45 )