Debian Codegraph @

django_jinja/backend.py

raw symbols SCIP
1 """
2 Since django 1.8.x, django comes with native multiple template engine support.
3 It also comes with jinja2 backend, but it is slightly unflexible, and it does
4 not support by default all django filters and related stuff.
5
6 This is an implementation of django backend inteface for use
7 django_jinja easy with django 1.8.
8 """
9
10 import sys
11 import os
12 import os.path as path
13 import functools
14 from importlib import import_module
15
16 import jinja2
17 from django.conf import settings
18 from django.core import signals
19 from django.core.exceptions import ImproperlyConfigured
20 from django.dispatch import receiver
21 from django.middleware import csrf
22 from django.template import TemplateDoesNotExist
23 from django.template import TemplateSyntaxError
24 from django.template.backends.base import BaseEngine
25 from django.template.context import BaseContext
26 from django.utils.encoding import smart_str
27 from django.utils.functional import SimpleLazyObject
28 from django.utils.functional import cached_property
29 from django.utils.module_loading import import_string
30 from django.utils.safestring import mark_safe
31
32 from . import base
33 from . import builtins
34 from . import library
35 from . import utils
36
37
38 class Origin:
39 """
40 A container to hold debug information as described in the template API
41 documentation.
42 """
43 def __init__(self, name, template_name):
44 self.name = name
45 self.template_name = template_name
46
47
48 class Template:
49 def __init__(self, template, backend):
50 self.template = template
51 self.backend = backend
52
53 self.name = template.name
54 self.origin = Origin(
55 name=template.filename, template_name=template.name
56 )
57
58 def render(self, context=None, request=None):
59 return mark_safe(self._process_template(self.template.render, context, request))
60
61 def stream(self, context=None, request=None):
62 return self._process_template(self.template.stream, context, request)
63
64 def _process_template(self, handler, context=None, request=None):
65 if context is None:
66 context = {}
67
68 context = base.dict_from_context(context)
69
70 if request is not None:
71 def _get_val():
72 token = csrf.get_token(request)
73 if token is None:
74 return 'NOTPROVIDED'
75 else:
76 return smart_str(token)
77
78 context["request"] = request
79 context["csrf_token"] = SimpleLazyObject(_get_val)
80
81 # Support for django context processors
82 for processor in self.backend.context_processors:
83 context.update(processor(request))
84
85 if self.backend._tmpl_debug:
86 from django.test import signals
87
88 # Define a "django" like context for emitatet the multi
89 # layered context object. This is mainly for apps like
90 # django-debug-toolbar that are very coupled to django's
91 # internal implementation of context.
92
93 if not isinstance(context, BaseContext):
94 class CompatibilityContext(dict):
95 @property
96 def dicts(self):
97 return [self]
98
99 context = CompatibilityContext(context)
100
101 signals.template_rendered.send(sender=self,
102 template=self,
103 context=context)
104
105 return handler(context)
106
107
108 class Jinja2(BaseEngine):
109 app_dirname = "templates"
110
111 @staticmethod
112 @functools.lru_cache()
113 def get_default():
114 """
115 When only one django-jinja backend is configured, returns it.
116 Raises ImproperlyConfigured otherwise.
117
118 This is required for finding the match extension where the
119 developer does not specify a template_engine on a
120 TemplateResponseMixin subclass.
121 """
122 from django.template import engines
123
124 jinja_engines = [engine for engine in engines.all()
125 if isinstance(engine, Jinja2)]
126 if len(jinja_engines) == 1:
127 # Unwrap the Jinja2 engine instance.
128 return jinja_engines[0]
129 elif len(jinja_engines) == 0:
130 raise ImproperlyConfigured(
131 "No Jinja2 backend is configured.")
132 else:
133 raise ImproperlyConfigured(
134 "Several Jinja2 backends are configured. "
135 "You must select one explicitly.")
136
137 def __init__(self, params):
138 params = params.copy()
139 options = params.pop("OPTIONS", {}).copy()
140
141 self.app_dirname = options.pop("app_dirname", "templates")
142 super().__init__(params)
143
144 newstyle_gettext = options.pop("newstyle_gettext", True)
145 context_processors = options.pop("context_processors", [])
146 match_extension = options.pop("match_extension", ".jinja")
147 match_regex = options.pop("match_regex", None)
148 environment_clspath = options.pop("environment", "jinja2.Environment")
149 extra_filters = options.pop("filters", {})
150 extra_tests = options.pop("tests", {})
151 extra_globals = options.pop("globals", {})
152 extra_constants = options.pop("constants", {})
153 translation_engine = options.pop("translation_engine", "django.utils.translation")
154 policies = options.pop("policies", {})
155
156 tmpl_debug = options.pop("debug", settings.DEBUG)
157 bytecode_cache = options.pop("bytecode_cache", {})
158 bytecode_cache.setdefault("name", "default")
159 bytecode_cache.setdefault("enabled", False)
160 bytecode_cache.setdefault("backend", "django_jinja.cache.BytecodeCache")
161
162 undefined = options.pop("undefined", None)
163 if undefined is not None:
164 if isinstance(undefined, str):
165 options["undefined"] = utils.load_class(undefined)
166 else:
167 options["undefined"] = undefined
168
169 if settings.DEBUG:
170 options.setdefault("undefined", jinja2.DebugUndefined)
171 else:
172 options.setdefault("undefined", jinja2.Undefined)
173
174 environment_cls = import_string(environment_clspath)
175
176 if isinstance(options.get("loader"), str):
177 # Allow to specify a loader as string
178 loader_cls = import_string(options.pop("loader"))
179 else:
180 # Backward compatible default
181 loader_cls = jinja2.FileSystemLoader
182
183 options.setdefault("loader", loader_cls(self.template_dirs))
184 options.setdefault("extensions", builtins.DEFAULT_EXTENSIONS)
185 options.setdefault("auto_reload", settings.DEBUG)
186 options.setdefault("autoescape", True)
187
188 self.env = environment_cls(**options)
189
190 # Initialize i18n support
191 if settings.USE_I18N:
192 translation = import_module(translation_engine)
193 self.env.install_gettext_translations(translation, newstyle=newstyle_gettext)
194 else:
195 self.env.install_null_translations(newstyle=newstyle_gettext)
196
197 self._context_processors = context_processors
198 self._match_regex = match_regex
199 self._match_extension = match_extension
200 self._tmpl_debug = tmpl_debug
201 self._bytecode_cache = bytecode_cache
202
203 self._initialize_builtins(filters=extra_filters,
204 tests=extra_tests,
205 globals=extra_globals,
206 constants=extra_constants)
207 self._initialize_policies(policies)
208
209 self._initialize_thirdparty()
210 self._initialize_bytecode_cache()
211
212 def _initialize_bytecode_cache(self):
213 if self._bytecode_cache["enabled"]:
214 cls = utils.load_class(self._bytecode_cache["backend"])
215 self.env.bytecode_cache = cls(self._bytecode_cache["name"])
216
217 def _initialize_thirdparty(self):
218 """
219 Iterate over all available apps in searching and preloading
220 available template filters or functions for jinja2.
221 """
222 for app_path, mod_path in base._iter_templatetags_modules_list():
223 if not path.isdir(mod_path):
224 continue
225
226 for filename in filter(lambda x: x.endswith(".py") or x.endswith(".pyc"), os.listdir(mod_path)):
227 # Exclude __init__.py files
228 if filename == "__init__.py" or filename == "__init__.pyc":
229 continue
230
231 file_mod_path = f"{app_path}.templatetags.{filename.rsplit('.', 1)[0]}"
232 try:
233 import_module(file_mod_path)
234 except ImportError:
235 pass
236
237 library._update_env(self.env)
238
239 def _initialize_builtins(self, filters=None, tests=None, globals=None, constants=None):
240 def insert(data, name, value):
241 if isinstance(value, str):
242 data[name] = import_string(value)
243 else:
244 data[name] = value
245
246 if filters:
247 for name, value in filters.items():
248 insert(self.env.filters, name, value)
249
250 if tests:
251 for name, value in tests.items():
252 insert(self.env.tests, name, value)
253
254 if globals:
255 for name, value in globals.items():
256 insert(self.env.globals, name, value)
257
258 if constants:
259 for name, value in constants.items():
260 self.env.globals[name] = value
261
262 def _initialize_policies(self, policies):
263 # Set policies like those in jinja2.defaults.DEFAULT_POLICIES
264 for name, value in policies.items():
265 self.env.policies[name] = value
266
267 @cached_property
268 def context_processors(self):
269 return tuple(import_string(path) for path in self._context_processors)
270
271 @property
272 def match_extension(self):
273 return self._match_extension
274
275 def from_string(self, template_code):
276 return Template(self.env.from_string(template_code), self)
277
278 def match_template(self, template_name):
279 return base.match_template(template_name,
280 self._match_extension,
281 self._match_regex)
282
283 def get_template(self, template_name):
284 if not self.match_template(template_name):
285 message = f"Template {template_name} does not exists"
286 raise TemplateDoesNotExist(message)
287
288 try:
289 return Template(self.env.get_template(template_name), self)
290 except jinja2.TemplateNotFound as exc:
291 # Unlike django's template engine, jinja2 doesn't like windows-style path separators.
292 # But because django does, its docs encourage the usage of os.path.join().
293 # Rather than insisting that our users switch to posixpath.join(), this try block
294 # will attempt to retrieve the template path again with forward slashes on windows:
295 if os.name == 'nt' and '\\' in template_name:
296 try:
297 return self.get_template(template_name.replace("\\", "/"))
298 except jinja2.TemplateNotFound:
299 pass
300
301 exc = TemplateDoesNotExist(exc.name, backend=self)
302
303 utils.reraise(
304 TemplateDoesNotExist,
305 exc,
306 sys.exc_info()[2],
307 )
308 except jinja2.TemplateSyntaxError as exc:
309 new = TemplateSyntaxError(exc.args)
310 new.template_debug = get_exception_info(exc)
311 utils.reraise(TemplateSyntaxError, new, sys.exc_info()[2])
312
313
314 @receiver(signals.setting_changed)
315 def _setting_changed(sender, setting, *args, **kwargs):
316 """ Reset the Jinja2.get_default() cached when TEMPLATES changes. """
317 if setting == "TEMPLATES":
318 Jinja2.get_default.cache_clear()
319
320
321 def get_exception_info(exception):
322 """
323 Formats exception information for display on the debug page using the
324 structure described in the template API documentation.
325 """
326 context_lines = 10
327 lineno = exception.lineno
328 if exception.source is None:
329 if os.path.exists(exception.filename):
330 with open(exception.filename) as f:
331 source = f.read()
332 else:
333 source = exception.source
334 lines = list(enumerate(source.strip().split("\n"), start=1))
335 during = lines[lineno - 1][1]
336 total = len(lines)
337 top = max(0, lineno - context_lines - 1)
338 bottom = min(total, lineno + context_lines)
339
340 return {
341 'name': exception.filename,
342 'message': exception.message,
343 'source_lines': lines[top:bottom],
344 'line': lineno,
345 'before': '',
346 'during': during,
347 'after': '',
348 'total': total,
349 'top': top,
350 'bottom': bottom,
351 }