Skip to content
Myr

Merge pull request #1114 from pallets/import-undefined

Before adoption: this commit came in with the history the project adopted, so no landing records it.

handle Undefined in get/select_template

authored by David Lord · committed by GitHub · parents 9176fbd, 2ec62dc · Browse files · 5 files+95 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+95 added−25 removed

  • tests:+25 added−0 removed
  • other:+70 added−25 removed

5 files+95 added−25 removed

modified:jinja2/environment.py+12 added-4 removed
23 unmodified lines
24from jinja2.nodes import EvalContext25from jinja2.compiler import generate, CodeGenerator26from jinja2.runtime import Undefined, new_context, Context27from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \28 TemplatesNotFound, TemplateRuntimeError28 TemplatesNotFound, TemplateRuntimeError, UndefinedError29from jinja2.utils import import_string, LRUCache, Markup, missing, \30 concat, consume, internalcode, have_async_gen31from jinja2._compat import imap, ifilter, string_types, iteritems, \32 text_type, reraise, implements_iterator, implements_to_string, \
778 unmodified lines
811 """Works like :meth:`get_template` but tries a number of templates812 before it fails. If it cannot find any of the templates, it will813 raise a :exc:`TemplatesNotFound` exception.814815 .. versionadded:: 2.3815 .. versionchanged:: 2.11816 If names is :class:`Undefined`, an :exc:`UndefinedError` is817 raised instead. If no templates were found and names818 contains :class:`Undefined`, the message is more helpful.819820 .. versionchanged:: 2.4821 If `names` contains a :class:`Template` object it is returned822 from the function unchanged.823824 .. versionadded:: 2.3825 """826 if isinstance(names, Undefined):827 names._fail_with_undefined_error()828829 if not names:830 raise TemplatesNotFound(message=u'Tried to select from an empty list '831 u'of templates.')832 globals = self.make_globals(globals)
3 unmodified lines
836 if parent is not None:837 name = self.join_path(name, parent)838 try:839 return self._load_template(name, globals)832 except TemplateNotFound:840 except (TemplateNotFound, UndefinedError):841 pass842 raise TemplatesNotFound(names)843844 @internalcode
4 unmodified lines
849 :meth:`get_template`.850851 .. versionadded:: 2.3852 """845 if isinstance(template_name_or_list, string_types):853 if isinstance(template_name_or_list, (string_types, Undefined)):854 return self.get_template(template_name_or_list, parent, globals)855 elif isinstance(template_name_or_list, Template):856 return template_name_or_list857 return self.select_template(template_name_or_list, parent, globals)
407 unmodified lines
modified:jinja2/exceptions.py+28 added-2 removed
41 unmodified lines
424344@implements_to_string45class TemplateNotFound(IOError, LookupError, TemplateError):46 """Raised if a template does not exist."""46 """Raised if a template does not exist.4748 .. versionchanged:: 2.1149 If the given name is :class:`Undefined` and no message was50 provided, an :exc:`UndefinedError` is raised.51 """5253 # looks weird, but removes the warning descriptor that just54 # bogusly warns us about message being deprecated55 message = None5657 def __init__(self, name, message=None):58 IOError.__init__(self, name)5960 if message is None:61 from jinja2.runtime import Undefined6263 if isinstance(name, Undefined):64 name._fail_with_undefined_error()6566 message = name6768 self.message = message69 self.name = name70 self.templates = [name]71
5 unmodified lines
77 """Like :class:`TemplateNotFound` but raised if multiple templates78 are selected. This is a subclass of :class:`TemplateNotFound`79 exception, so just catching the base exception will catch both.8081 .. versionchanged:: 2.1182 If a name in the list of names is :class:`Undefined`, a message83 about it being undefined is shown rather than the empty string.8485 .. versionadded:: 2.286 """8788 def __init__(self, names=(), message=None):89 if message is None:90 from jinja2.runtime import Undefined9192 parts = []9394 for name in names:95 if isinstance(name, Undefined):96 parts.append(name._undefined_message)97 else:98 parts.append(name)99100 message = u'none of the templates given were found: ' + \75 u', '.join(imap(text_type, names))101 u', '.join(imap(text_type, parts))102 TemplateNotFound.__init__(self, names and names[-1] or None, message)103 self.templates = list(names)104105
67 unmodified lines
modified:jinja2/runtime.py+25 added-18 removed
666 unmodified lines
667 self._undefined_obj = obj668 self._undefined_name = name669 self._undefined_exception = exc670671 @property672 def _undefined_message(self):673 """Build a message about the undefined value based on how it was674 accessed.675 """676 if self._undefined_hint:677 return self._undefined_hint678679 if self._undefined_obj is missing:680 return '%r is undefined' % self._undefined_name681682 if not isinstance(self._undefined_name, string_types):683 return '%s has no element %r' % (684 object_type_repr(self._undefined_obj),685 self._undefined_name686 )687688 return '%r has no attribute %r' % (689 object_type_repr(self._undefined_obj),690 self._undefined_name691 )692693 @internalcode694 def _fail_with_undefined_error(self, *args, **kwargs):673 """Regular callback function for undefined objects that raises an674 `UndefinedError` on call.695 """Raise an :exc:`UndefinedError` when operations are performed696 on the undefined value.697 """676 if self._undefined_hint is None:677 if self._undefined_obj is missing:678 hint = '%r is undefined' % self._undefined_name679 elif not isinstance(self._undefined_name, string_types):680 hint = '%s has no element %r' % (681 object_type_repr(self._undefined_obj),682 self._undefined_name683 )684 else:685 hint = '%r has no attribute %r' % (686 object_type_repr(self._undefined_obj),687 self._undefined_name688 )689 else:690 hint = self._undefined_hint691 raise self._undefined_exception(hint)698 raise self._undefined_exception(self._undefined_message)699700 @internalcode701 def __getattr__(self, name):702 if name[:2] == '__':
204 unmodified lines
modified:tests/test_api.py+25 added
15 unmodified lines
16import pytest17from jinja2 import Environment, Undefined, ChainableUndefined, \18 DebugUndefined, StrictUndefined, UndefinedError, meta, \19 is_undefined, Template, DictLoader, make_logging_undefined20from jinja2 import TemplatesNotFound21from jinja2.compiler import CodeGenerator22from jinja2.runtime import Context23from jinja2.utils import Cycler24from jinja2.utils import contextfunction
100 unmodified lines
125 assert env.select_template([t]) is t126 assert env.get_or_select_template([t]) is t127 assert env.get_or_select_template(t) is t128129 def test_get_template_undefined(self, env):130 """Passing Undefined to get/select_template raises an131 UndefinedError or shows the undefined message in the list.132 """133 env.loader=DictLoader({})134 t = Undefined(name="no_name_1")135136 with pytest.raises(UndefinedError):137 env.get_template(t)138139 with pytest.raises(UndefinedError):140 env.get_or_select_template(t)141142 with pytest.raises(UndefinedError):143 env.select_template(t)144145 with pytest.raises(TemplatesNotFound) as exc_info:146 env.select_template([t, "no_name_2"])147148 exc_message = str(exc_info.value)149 assert "'no_name_1' is undefined" in exc_message150 assert "no_name_2" in exc_message151152153 def test_autoescape_autoselect(self, env):154 def select_autoescape(name):155 if name is None or '.' not in name:156 return False
284 unmodified lines
modified:CHANGES.rst+5 added-1 removed
92 unmodified lines
93- Constant folding during compilation is applied to some node types94 that were previously overlooked. :issue:`733`95- ``TemplateSyntaxError.source`` is not empty when raised from an96 included template. :issue:`457`97- Passing an ``Undefined`` value to ``get_template`` (such as through98 ``extends``, ``import``, or ``include``), raises an99 ``UndefinedError`` consistently. ``select_template`` will show the100 undefined message in the list of attempts rather than the empty101 string. :issue:`1037`10298103Version 2.10.3104--------------105106Released 2019-10-04
627 unmodified lines