2007-07-23 12:45:01 +08:00
|
|
|
"""
|
|
|
|
Wrapper for loading templates from the filesystem.
|
|
|
|
"""
|
2005-09-29 23:06:53 +08:00
|
|
|
|
2015-03-03 03:31:14 +08:00
|
|
|
import errno
|
2014-11-12 05:36:41 +08:00
|
|
|
import io
|
2015-03-04 05:48:26 +08:00
|
|
|
import warnings
|
2014-11-12 05:36:41 +08:00
|
|
|
|
2014-11-12 01:59:49 +08:00
|
|
|
from django.core.exceptions import SuspiciousFileOperation
|
2015-03-04 05:48:26 +08:00
|
|
|
from django.template.base import Origin, TemplateDoesNotExist
|
2007-07-23 12:45:01 +08:00
|
|
|
from django.utils._os import safe_join
|
2015-03-04 05:48:26 +08:00
|
|
|
from django.utils.deprecation import RemovedInDjango21Warning
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2014-11-16 01:35:02 +08:00
|
|
|
from .base import Loader as BaseLoader
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
class Loader(BaseLoader):
|
|
|
|
|
2015-02-24 23:17:17 +08:00
|
|
|
def get_dirs(self):
|
|
|
|
return self.engine.dirs
|
|
|
|
|
2015-03-04 05:48:26 +08:00
|
|
|
def get_contents(self, origin):
|
|
|
|
try:
|
|
|
|
with io.open(origin.name, encoding=self.engine.file_charset) as fp:
|
|
|
|
return fp.read()
|
|
|
|
except IOError as e:
|
|
|
|
if e.errno == errno.ENOENT:
|
|
|
|
raise TemplateDoesNotExist(origin)
|
|
|
|
raise
|
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
def get_template_sources(self, template_name, template_dirs=None):
|
|
|
|
"""
|
2015-03-04 05:48:26 +08:00
|
|
|
Return an Origin object pointing to an absolute path in each directory
|
|
|
|
in template_dirs. For security reasons, if a path doesn't lie inside
|
|
|
|
one of the template_dirs it is excluded from the result set.
|
2009-12-14 20:08:23 +08:00
|
|
|
"""
|
|
|
|
if not template_dirs:
|
2015-02-24 23:17:17 +08:00
|
|
|
template_dirs = self.get_dirs()
|
2009-12-14 20:08:23 +08:00
|
|
|
for template_dir in template_dirs:
|
|
|
|
try:
|
2015-03-04 05:48:26 +08:00
|
|
|
name = safe_join(template_dir, template_name)
|
2014-11-12 01:59:49 +08:00
|
|
|
except SuspiciousFileOperation:
|
|
|
|
# The joined path was located outside of this template_dir
|
|
|
|
# (it might be inside another one, so this isn't fatal).
|
2015-03-04 05:48:26 +08:00
|
|
|
continue
|
|
|
|
|
|
|
|
yield Origin(
|
|
|
|
name=name,
|
|
|
|
template_name=template_name,
|
|
|
|
loader=self,
|
|
|
|
)
|
2009-12-14 20:08:23 +08:00
|
|
|
|
|
|
|
def load_template_source(self, template_name, template_dirs=None):
|
2015-03-04 05:48:26 +08:00
|
|
|
warnings.warn(
|
|
|
|
'The load_template_sources() method is deprecated. Use '
|
|
|
|
'get_template() or get_contents() instead.',
|
|
|
|
RemovedInDjango21Warning,
|
|
|
|
)
|
|
|
|
for origin in self.get_template_sources(template_name, template_dirs):
|
2009-12-14 20:08:23 +08:00
|
|
|
try:
|
2015-03-04 05:48:26 +08:00
|
|
|
return self.get_contents(origin), origin.name
|
|
|
|
except TemplateDoesNotExist:
|
|
|
|
pass
|
2015-02-24 23:17:17 +08:00
|
|
|
raise TemplateDoesNotExist(template_name)
|