Merge pull request #1190 from pallets/native-eval
Before adoption: this commit came in with the history the project adopted, so no landing records it.
native only evals at end of render
authored by David Lord · committed by GitHub · parents f1756a3, f75cb42 · Browse files · 3 files·+20 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+20 added−24 removed
- tests:+9 added−0 removed
- other:+11 added−24 removed
Provenance
- Commit
179df6b- Tree
571a880- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
f1756a3- Parent 2
f75cb42
3 files changed+20 added−24 removed
modified:src/jinja2/nativetypes.py+7 added-24 removed
1-import types1 from ast import literal_eval2 from itertools import chain3 from itertools import islice4 4 unmodified lines9 from .environment import Environment10 from .environment import Template11 12 14-def native_concat(nodes, preserve_quotes=True):13+def native_concat(nodes):14 """Return a native Python type from the list of compiled nodes. If15 the result is a single node, its value is returned. Otherwise, the16 nodes are concatenated as strings. If the result can be parsed with17 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,18 the string is returned.19 20 :param nodes: Iterable of nodes to concatenate.22- :param preserve_quotes: Whether to re-wrap literal strings with23- quotes, to preserve quotes around expressions for later parsing.24- Should be ``False`` in :meth:`NativeEnvironment.render`.21 """22 head = list(islice(nodes, 2))23 24 if not head:1 unmodified line26 27 if len(head) == 1:28 raw = head[0]29 else:34- if isinstance(nodes, types.GeneratorType):35- nodes = chain(head, nodes)36- raw = u"".join([text_type(v) for v in nodes])30+ raw = u"".join([text_type(v) for v in chain(head, nodes)])31 32 try:39- literal = literal_eval(raw)33+ return literal_eval(raw)34 except (ValueError, SyntaxError, MemoryError):35 return raw36 43- # If literal_eval returned a string, re-wrap with the original44- # quote character to avoid dropping quotes between expression nodes.45- # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46- # be ('a', 'b').47- if preserve_quotes and isinstance(literal, str):48- return "{quote}{}{quote}".format(literal, quote=raw[0])37 50- return literal51-52-38 class NativeCodeGenerator(CodeGenerator):39 """A code generator which renders Python types by not adding55- ``to_string()`` around output nodes, and using :func:`native_concat`56- to convert complex strings back to Python types if possible.40+ ``to_string()`` around output nodes.41 """42 43 @staticmethod44 def _default_finalize(value):45 return value46 47 def _output_const_repr(self, group):64- return repr(native_concat(group))48+ return repr(u"".join([text_type(v) for v in group]))49 50 def _output_child_to_const(self, node, frame, finalize):51 const = node.as_const(frame.eval_ctx)52 30 unmodified lines83 with :func:`ast.literal_eval`, the parsed value is returned.84 Otherwise, the string is returned.85 """86 vars = dict(*args, **kwargs)87+88 try:104- return native_concat(105- self.root_render_func(self.new_context(vars)), preserve_quotes=False106- )89+ return native_concat(self.root_render_func(self.new_context(vars)))90 except Exception:91 return self.environment.handle_exception()92 93 1 unmodified linemodified:tests/test_nativetypes.py+9 added
132 unmodified lines133 result = t.render(host="localhost", user="Jinja")134 assert result == "--host='localhost' --user \"Jinja\""135 136 137+def test_no_intermediate_eval(env):138+ t = env.from_string("0.000{{ a }}")139+ result = t.render(a=7)140+ assert isinstance(result, float)141+ # If intermediate eval happened, 0.000 would render 0.0, then 7142+ # would be appended, resulting in 0.07.143+ assert result < 0.007 # TODO use math.isclose in Python 3144+145+146 def test_spontaneous_env():147 t = NativeTemplate("{{ true }}")148 assert isinstance(t.environment, NativeEnvironment)modified:CHANGES.rst+4 added
25 unmodified lines26 - The special ``namespace()`` assignment object in templates works in27 async environments. :issue:`1180`28 - Fix whitespace being removed before tags in the middle of lines when29 ``lstrip_blocks`` is enabled. :issue:`1138`30+- :class:`~nativetypes.NativeEnvironment` doesn't evaluate31+ intermediate strings during rendering. This prevents early32+ evaluation which could change the value of an expression.33+ :issue:`1186`34 35 36 Version 2.11.137 --------------737 unmodified lines