Merge pull request #708 from jctanner/NATIVE_TYPES
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add support for the Environment to optionally return native types.
authored by David Lord · committed by GitHub · parents 31f92b5, 6a7a263 · Browse files · 5 files·+399 added−1 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+399 added−1 removed
- tests:+110 added−0 removed
- other:+289 added−1 removed
Provenance
- Commit
d17c7db- Tree
9849547- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
31f92b5- Parent 2
6a7a263
5 files changed+399 added−1 removed
modified:docs/contents.rst.inc+1 added
5 unmodified lines6 7 intro8 api9 sandbox10+ nativetypes11 templates12 extensions13 integration14 switching10 unmodified linesadded:docs/nativetypes.rst+64 added
1+.. module:: jinja2.nativetypes2+3+.. _nativetypes:4+5+Native Python Types6+===================7+8+The default :class:`~jinja2.Environment` renders templates to strings. With9+:class:`NativeEnvironment`, rendering a template produces a native Python type.10+This is useful if you are using Jinja outside the context of creating text11+files. For example, your code may have an intermediate step where users may use12+templates to define values that will then be passed to a traditional string13+environment.14+15+Examples16+--------17+18+Adding two values results in an integer, not a string with a number:19+20+>>> env = NativeEnvironment()21+>>> t = env.from_string('{{ x + y }}')22+>>> result = t.render(x=4, y=2)23+>>> print(result)24+625+>>> print(type(result))26+int27+28+Rendering list syntax produces a list:29+30+>>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]')31+>>> result = t.render(data=range(5))32+>>> print(result)33+[1, 2, 3, 4, 5]34+>>> print(type(result))35+list36+37+Rendering something that doesn't look like a Python literal produces a string:38+39+>>> t = env.from_string('{{ x }} * {{ y }}')40+>>> result = t.render(x=4, y=2)41+>>> print(result)42+4 * 243+>>> print(type(result))44+str45+46+Rendering a Python object produces that object as long as it is the only node:47+48+>>> class Foo:49+... def __init__(self, value):50+... self.value = value51+...52+>>> result = env.from_string('{{ x }}').render(x=Foo(15))53+>>> print(type(result).__name__)54+Foo55+>>> print(result.value)56+1557+58+API59+---60+61+.. autoclass:: NativeEnvironment([options])62+63+.. autoclass:: NativeTemplate([options])64+ :members: renderadded:jinja2/nativetypes.py+220 added
1+import sys2+from ast import literal_eval3+from itertools import islice, chain4+from jinja2 import nodes5+from jinja2._compat import text_type6+from jinja2.compiler import CodeGenerator, has_safe_repr7+from jinja2.environment import Environment, Template8+from jinja2.utils import concat, escape9+10+11+def native_concat(nodes):12+ """Return a native Python type from the list of compiled nodes. If the13+ result is a single node, its value is returned. Otherwise, the nodes are14+ concatenated as strings. If the result can be parsed with15+ :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the16+ string is returned.17+ """18+ head = list(islice(nodes, 2))19+20+ if not head:21+ return None22+23+ if len(head) == 1:24+ out = head[0]25+ else:26+ out = u''.join([text_type(v) for v in chain(head, nodes)])27+28+ try:29+ return literal_eval(out)30+ except (ValueError, SyntaxError, MemoryError):31+ return out32+33+34+class NativeCodeGenerator(CodeGenerator):35+ """A code generator which avoids injecting ``to_string()`` calls around the36+ internal code Jinja uses to render templates.37+ """38+39+ def visit_Output(self, node, frame):40+ """Same as :meth:`CodeGenerator.visit_Output`, but do not call41+ ``to_string`` on output nodes in generated code.42+ """43+ if self.has_known_extends and frame.require_output_check:44+ return45+46+ finalize = self.environment.finalize47+ finalize_context = getattr(finalize, 'contextfunction', False)48+ finalize_eval = getattr(finalize, 'evalcontextfunction', False)49+ finalize_env = getattr(finalize, 'environmentfunction', False)50+51+ if finalize is not None:52+ if finalize_context or finalize_eval:53+ const_finalize = None54+ elif finalize_env:55+ def const_finalize(x):56+ return finalize(self.environment, x)57+ else:58+ const_finalize = finalize59+ else:60+ def const_finalize(x):61+ return x62+63+ # If we are inside a frame that requires output checking, we do so.64+ outdent_later = False65+66+ if frame.require_output_check:67+ self.writeline('if parent_template is None:')68+ self.indent()69+ outdent_later = True70+71+ # Try to evaluate as many chunks as possible into a static string at72+ # compile time.73+ body = []74+75+ for child in node.nodes:76+ try:77+ if const_finalize is None:78+ raise nodes.Impossible()79+80+ const = child.as_const(frame.eval_ctx)81+ if not has_safe_repr(const):82+ raise nodes.Impossible()83+ except nodes.Impossible:84+ body.append(child)85+ continue86+87+ # the frame can't be volatile here, because otherwise the as_const88+ # function would raise an Impossible exception at that point89+ try:90+ if frame.eval_ctx.autoescape:91+ if hasattr(const, '__html__'):92+ const = const.__html__()93+ else:94+ const = escape(const)95+96+ const = const_finalize(const)97+ except Exception:98+ # if something goes wrong here we evaluate the node at runtime99+ # for easier debugging100+ body.append(child)101+ continue102+103+ if body and isinstance(body[-1], list):104+ body[-1].append(const)105+ else:106+ body.append([const])107+108+ # if we have less than 3 nodes or a buffer we yield or extend/append109+ if len(body) < 3 or frame.buffer is not None:110+ if frame.buffer is not None:111+ # for one item we append, for more we extend112+ if len(body) == 1:113+ self.writeline('%s.append(' % frame.buffer)114+ else:115+ self.writeline('%s.extend((' % frame.buffer)116+117+ self.indent()118+119+ for item in body:120+ if isinstance(item, list):121+ val = repr(native_concat(item))122+123+ if frame.buffer is None:124+ self.writeline('yield ' + val)125+ else:126+ self.writeline(val + ',')127+ else:128+ if frame.buffer is None:129+ self.writeline('yield ', item)130+ else:131+ self.newline(item)132+133+ close = 0134+135+ if finalize is not None:136+ self.write('environment.finalize(')137+138+ if finalize_context:139+ self.write('context, ')140+141+ close += 1142+143+ self.visit(item, frame)144+145+ if close > 0:146+ self.write(')' * close)147+148+ if frame.buffer is not None:149+ self.write(',')150+151+ if frame.buffer is not None:152+ # close the open parentheses153+ self.outdent()154+ self.writeline(len(body) == 1 and ')' or '))')155+156+ # otherwise we create a format string as this is faster in that case157+ else:158+ format = []159+ arguments = []160+161+ for item in body:162+ if isinstance(item, list):163+ format.append(native_concat(item).replace('%', '%%'))164+ else:165+ format.append('%s')166+ arguments.append(item)167+168+ self.writeline('yield ')169+ self.write(repr(concat(format)) + ' % (')170+ self.indent()171+172+ for argument in arguments:173+ self.newline(argument)174+ close = 0175+176+ if finalize is not None:177+ self.write('environment.finalize(')178+179+ if finalize_context:180+ self.write('context, ')181+ elif finalize_eval:182+ self.write('context.eval_ctx, ')183+ elif finalize_env:184+ self.write('environment, ')185+186+ close += 1187+188+ self.visit(argument, frame)189+ self.write(')' * close + ', ')190+191+ self.outdent()192+ self.writeline(')')193+194+ if outdent_later:195+ self.outdent()196+197+198+class NativeTemplate(Template):199+ def render(self, *args, **kwargs):200+ """Render the template to produce a native Python type. If the result201+ is a single node, its value is returned. Otherwise, the nodes are202+ concatenated as strings. If the result can be parsed with203+ :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the204+ string is returned.205+ """206+ vars = dict(*args, **kwargs)207+208+ try:209+ return native_concat(self.root_render_func(self.new_context(vars)))210+ except Exception:211+ exc_info = sys.exc_info()212+213+ return self.environment.handle_exception(exc_info, True)214+215+216+class NativeEnvironment(Environment):217+ """An environment that renders templates to native Python types."""218+219+ code_generator_class = NativeCodeGenerator220+ template_class = NativeTemplateadded:tests/test_nativetypes.py+110 added
1+import pytest2+3+from jinja2._compat import text_type4+from jinja2.exceptions import UndefinedError5+from jinja2.nativetypes import NativeEnvironment6+from jinja2.runtime import Undefined7+8+9+@pytest.fixture10+def env():11+ return NativeEnvironment()12+13+14+class TestNativeEnvironment(object):15+ def test_is_defined_native_return(self, env):16+ t = env.from_string('{{ missing is defined }}')17+ assert not t.render()18+19+ def test_undefined_native_return(self, env):20+ t = env.from_string('{{ missing }}')21+ assert isinstance(t.render(), Undefined)22+23+ def test_adding_undefined_native_return(self, env):24+ t = env.from_string('{{ 3 + missing }}')25+26+ with pytest.raises(UndefinedError):27+ t.render()28+29+ def test_cast_int(self, env):30+ t = env.from_string("{{ anumber|int }}")31+ result = t.render(anumber='3')32+ assert isinstance(result, int)33+ assert result == 334+35+ def test_list_add(self, env):36+ t = env.from_string("{{ listone + listtwo }}")37+ result = t.render(listone=['a', 'b'], listtwo=['c', 'd'])38+ assert isinstance(result, list)39+ assert result == ['a', 'b', 'c', 'd']40+41+ def test_multi_expression_add(self, env):42+ t = env.from_string("{{ listone }} + {{ listtwo }}")43+ result = t.render(listone=['a', 'b'], listtwo=['c', 'd'])44+ assert not isinstance(result, list)45+ assert result == "['a', 'b'] + ['c', 'd']"46+47+ def test_loops(self, env):48+ t = env.from_string("{% for x in listone %}{{ x }}{% endfor %}")49+ result = t.render(listone=['a', 'b', 'c', 'd'])50+ assert isinstance(result, text_type)51+ assert result == 'abcd'52+53+ def test_loops_with_ints(self, env):54+ t = env.from_string("{% for x in listone %}{{ x }}{% endfor %}")55+ result = t.render(listone=[1, 2, 3, 4])56+ assert isinstance(result, int)57+ assert result == 123458+59+ def test_loop_look_alike(self, env):60+ t = env.from_string("{% for x in listone %}{{ x }}{% endfor %}")61+ result = t.render(listone=[1])62+ assert isinstance(result, int)63+ assert result == 164+65+ def test_booleans(self, env):66+ t = env.from_string("{{ boolval }}")67+ result = t.render(boolval=True)68+ assert isinstance(result, bool)69+ assert result is True70+71+ t = env.from_string("{{ boolval }}")72+ result = t.render(boolval=False)73+ assert isinstance(result, bool)74+ assert result is False75+76+ t = env.from_string("{{ 1 == 1 }}")77+ result = t.render()78+ assert isinstance(result, bool)79+ assert result is True80+81+ t = env.from_string("{{ 2 + 2 == 5 }}")82+ result = t.render()83+ assert isinstance(result, bool)84+ assert result is False85+86+ t = env.from_string("{{ None == None }}")87+ result = t.render()88+ assert isinstance(result, bool)89+ assert result is True90+91+ t = env.from_string("{{ '' == None }}")92+ result = t.render()93+ assert isinstance(result, bool)94+ assert result is False95+96+ def test_variable_dunder(self, env):97+ t = env.from_string("{{ x.__class__ }}")98+ result = t.render(x=True)99+ assert isinstance(result, type)100+101+ def test_constant_dunder(self, env):102+ t = env.from_string("{{ true.__class__ }}")103+ result = t.render()104+ assert isinstance(result, type)105+106+ def test_constant_dunder_to_string(self, env):107+ t = env.from_string("{{ true.__class__|string }}")108+ result = t.render()109+ assert not isinstance(result, type)110+ assert result in ["<type 'bool'>", "<class 'bool'>"]modified:CHANGES+4 added-1 removed
28 unmodified lines29 - Added tests for all comparison operators: ``eq``, ``ne``, ``lt``, ``le``,30 ``gt``, ``ge``. (`#665`_)31 - ``import`` statement cannot end with a trailing comma. (`#617`_, `#618`_)32 - ``indent`` filter will not indent blank lines by default. (`#685`_)33-- Added ``reverse`` argument for ``dictsort`` filter. (`#692`_)33+- Add ``reverse`` argument for ``dictsort`` filter. (`#692`_)34+- Add a ``NativeEnvironment`` that renders templates to native Python types35+ instead of strings. (`#708`_)36 37 .. _#469: https://github.com/pallets/jinja/pull/46938 .. _#475: https://github.com/pallets/jinja/pull/47539 .. _#478: https://github.com/pallets/jinja/pull/4781 unmodified line41 .. _#618: https://github.com/pallets/jinja/pull/61842 .. _#665: https://github.com/pallets/jinja/pull/66543 .. _#685: https://github.com/pallets/jinja/pull/68544 .. _#692: https://github.com/pallets/jinja/pull/69245+.. _#708: https://github.com/pallets/jinja/pull/70846 47 Version 2.9.748 -------------49 519 unmodified lines