PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/google/appengine/_internal/django/template/loader.py

https://github.com/theosp/google_appengine
Python | 198 lines | 116 code | 21 blank | 61 comment | 34 complexity | 5b954798d1700ad09eab0cd857e5e8b5 MD5 | raw file
  1. # Wrapper for loading templates from storage of some sort (e.g. filesystem, database).
  2. #
  3. # This uses the TEMPLATE_LOADERS setting, which is a list of loaders to use.
  4. # Each loader is expected to have this interface:
  5. #
  6. # callable(name, dirs=[])
  7. #
  8. # name is the template name.
  9. # dirs is an optional list of directories to search instead of TEMPLATE_DIRS.
  10. #
  11. # The loader should return a tuple of (template_source, path). The path returned
  12. # might be shown to the user for debugging purposes, so it should identify where
  13. # the template was loaded from.
  14. #
  15. # A loader may return an already-compiled template instead of the actual
  16. # template source. In that case the path returned should be None, since the
  17. # path information is associated with the template during the compilation,
  18. # which has already been done.
  19. #
  20. # Each loader should have an "is_usable" attribute set. This is a boolean that
  21. # specifies whether the loader can be used in this Python installation. Each
  22. # loader is responsible for setting this when it's initialized.
  23. #
  24. # For example, the eggs loader (which is capable of loading templates from
  25. # Python eggs) sets is_usable to False if the "pkg_resources" module isn't
  26. # installed, because pkg_resources is necessary to read eggs.
  27. from google.appengine._internal.django.core.exceptions import ImproperlyConfigured
  28. from google.appengine._internal.django.template import Origin, Template, Context, TemplateDoesNotExist, add_to_builtins
  29. from google.appengine._internal.django.utils.importlib import import_module
  30. from google.appengine._internal.django.conf import settings
  31. template_source_loaders = None
  32. class BaseLoader(object):
  33. is_usable = False
  34. def __init__(self, *args, **kwargs):
  35. pass
  36. def __call__(self, template_name, template_dirs=None):
  37. return self.load_template(template_name, template_dirs)
  38. def load_template(self, template_name, template_dirs=None):
  39. source, display_name = self.load_template_source(template_name, template_dirs)
  40. origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
  41. try:
  42. template = get_template_from_string(source, origin, template_name)
  43. return template, None
  44. except TemplateDoesNotExist:
  45. # If compiling the template we found raises TemplateDoesNotExist, back off to
  46. # returning the source and display name for the template we were asked to load.
  47. # This allows for correct identification (later) of the actual template that does
  48. # not exist.
  49. return source, display_name
  50. def load_template_source(self, template_name, template_dirs=None):
  51. """
  52. Returns a tuple containing the source and origin for the given template
  53. name.
  54. """
  55. raise NotImplementedError
  56. def reset(self):
  57. """
  58. Resets any state maintained by the loader instance (e.g., cached
  59. templates or cached loader modules).
  60. """
  61. pass
  62. class LoaderOrigin(Origin):
  63. def __init__(self, display_name, loader, name, dirs):
  64. super(LoaderOrigin, self).__init__(display_name)
  65. self.loader, self.loadname, self.dirs = loader, name, dirs
  66. def reload(self):
  67. return self.loader(self.loadname, self.dirs)[0]
  68. def make_origin(display_name, loader, name, dirs):
  69. if settings.TEMPLATE_DEBUG and display_name:
  70. return LoaderOrigin(display_name, loader, name, dirs)
  71. else:
  72. return None
  73. def find_template_loader(loader):
  74. if isinstance(loader, (tuple, list)):
  75. loader, args = loader[0], loader[1:]
  76. else:
  77. args = []
  78. if isinstance(loader, basestring):
  79. module, attr = loader.rsplit('.', 1)
  80. try:
  81. mod = import_module(module)
  82. except ImportError, e:
  83. raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
  84. try:
  85. TemplateLoader = getattr(mod, attr)
  86. except AttributeError, e:
  87. raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
  88. if hasattr(TemplateLoader, 'load_template_source'):
  89. func = TemplateLoader(*args)
  90. else:
  91. # Try loading module the old way - string is full path to callable
  92. if args:
  93. raise ImproperlyConfigured("Error importing template source loader %s - can't pass arguments to function-based loader." % loader)
  94. func = TemplateLoader
  95. if not func.is_usable:
  96. import warnings
  97. warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % loader)
  98. return None
  99. else:
  100. return func
  101. else:
  102. raise ImproperlyConfigured('Loader does not define a "load_template" callable template source loader')
  103. def find_template(name, dirs=None):
  104. # Calculate template_source_loaders the first time the function is executed
  105. # because putting this logic in the module-level namespace may cause
  106. # circular import errors. See Django ticket #1292.
  107. global template_source_loaders
  108. if template_source_loaders is None:
  109. loaders = []
  110. for loader_name in settings.TEMPLATE_LOADERS:
  111. loader = find_template_loader(loader_name)
  112. if loader is not None:
  113. loaders.append(loader)
  114. template_source_loaders = tuple(loaders)
  115. for loader in template_source_loaders:
  116. try:
  117. source, display_name = loader(name, dirs)
  118. return (source, make_origin(display_name, loader, name, dirs))
  119. except TemplateDoesNotExist:
  120. pass
  121. raise TemplateDoesNotExist(name)
  122. def find_template_source(name, dirs=None):
  123. # For backward compatibility
  124. import warnings
  125. warnings.warn(
  126. "`django.template.loaders.find_template_source` is deprecated; use `django.template.loaders.find_template` instead.",
  127. PendingDeprecationWarning
  128. )
  129. template, origin = find_template(name, dirs)
  130. if hasattr(template, 'render'):
  131. raise Exception("Found a compiled template that is incompatible with the deprecated `django.template.loaders.find_template_source` function.")
  132. return template, origin
  133. def get_template(template_name):
  134. """
  135. Returns a compiled Template object for the given template name,
  136. handling template inheritance recursively.
  137. """
  138. template, origin = find_template(template_name)
  139. if not hasattr(template, 'render'):
  140. # template needs to be compiled
  141. template = get_template_from_string(template, origin, template_name)
  142. return template
  143. def get_template_from_string(source, origin=None, name=None):
  144. """
  145. Returns a compiled Template object for the given template code,
  146. handling template inheritance recursively.
  147. """
  148. return Template(source, origin, name)
  149. def render_to_string(template_name, dictionary=None, context_instance=None):
  150. """
  151. Loads the given template_name and renders it with the given dictionary as
  152. context. The template_name may be a string to load a single template using
  153. get_template, or it may be a tuple to use select_template to find one of
  154. the templates in the list. Returns a string.
  155. """
  156. dictionary = dictionary or {}
  157. if isinstance(template_name, (list, tuple)):
  158. t = select_template(template_name)
  159. else:
  160. t = get_template(template_name)
  161. if context_instance:
  162. context_instance.update(dictionary)
  163. else:
  164. context_instance = Context(dictionary)
  165. return t.render(context_instance)
  166. def select_template(template_name_list):
  167. "Given a list of template names, returns the first that can be loaded."
  168. for template_name in template_name_list:
  169. try:
  170. return get_template(template_name)
  171. except TemplateDoesNotExist:
  172. continue
  173. # If we get here, none of the templates could be loaded
  174. raise TemplateDoesNotExist(', '.join(template_name_list))
  175. add_to_builtins('google.appengine._internal.django.template.loader_tags')