Skip to content
Myr

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

5 files+399 added−1 removed

modified:docs/contents.rst.inc+1 added
5 unmodified lines
67 intro8 api9 sandbox10 nativetypes11 templates12 extensions13 integration14 switching
10 unmodified lines
added:docs/nativetypes.rst+64 added
1.. module:: jinja2.nativetypes23.. _nativetypes:45Native Python Types6===================78The default :class:`~jinja2.Environment` renders templates to strings. With9:class:`NativeEnvironment`, rendering a template produces a native Python type.10This is useful if you are using Jinja outside the context of creating text11files. For example, your code may have an intermediate step where users may use12templates to define values that will then be passed to a traditional string13environment.1415Examples16--------1718Adding two values results in an integer, not a string with a number:1920>>> env = NativeEnvironment()21>>> t = env.from_string('{{ x + y }}')22>>> result = t.render(x=4, y=2)23>>> print(result)24625>>> print(type(result))26int2728Rendering list syntax produces a list:2930>>> 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))35list3637Rendering something that doesn't look like a Python literal produces a string:3839>>> t = env.from_string('{{ x }} * {{ y }}')40>>> result = t.render(x=4, y=2)41>>> print(result)424 * 243>>> print(type(result))44str4546Rendering a Python object produces that object as long as it is the only node:4748>>> 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__)54Foo55>>> print(result.value)56155758API59---6061.. autoclass:: NativeEnvironment([options])6263.. autoclass:: NativeTemplate([options])64 :members: render
added:jinja2/nativetypes.py+220 added
1import sys2from ast import literal_eval3from itertools import islice, chain4from jinja2 import nodes5from jinja2._compat import text_type6from jinja2.compiler import CodeGenerator, has_safe_repr7from jinja2.environment import Environment, Template8from jinja2.utils import concat, escape91011def 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))1920 if not head:21 return None2223 if len(head) == 1:24 out = head[0]25 else:26 out = u''.join([text_type(v) for v in chain(head, nodes)])2728 try:29 return literal_eval(out)30 except (ValueError, SyntaxError, MemoryError):31 return out323334class NativeCodeGenerator(CodeGenerator):35 """A code generator which avoids injecting ``to_string()`` calls around the36 internal code Jinja uses to render templates.37 """3839 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 return4546 finalize = self.environment.finalize47 finalize_context = getattr(finalize, 'contextfunction', False)48 finalize_eval = getattr(finalize, 'evalcontextfunction', False)49 finalize_env = getattr(finalize, 'environmentfunction', False)5051 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 x6263 # If we are inside a frame that requires output checking, we do so.64 outdent_later = False6566 if frame.require_output_check:67 self.writeline('if parent_template is None:')68 self.indent()69 outdent_later = True7071 # Try to evaluate as many chunks as possible into a static string at72 # compile time.73 body = []7475 for child in node.nodes:76 try:77 if const_finalize is None:78 raise nodes.Impossible()7980 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 continue8687 # 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)9596 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 continue102103 if body and isinstance(body[-1], list):104 body[-1].append(const)105 else:106 body.append([const])107108 # 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)116117 self.indent()118119 for item in body:120 if isinstance(item, list):121 val = repr(native_concat(item))122123 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)132133 close = 0134135 if finalize is not None:136 self.write('environment.finalize(')137138 if finalize_context:139 self.write('context, ')140141 close += 1142143 self.visit(item, frame)144145 if close > 0:146 self.write(')' * close)147148 if frame.buffer is not None:149 self.write(',')150151 if frame.buffer is not None:152 # close the open parentheses153 self.outdent()154 self.writeline(len(body) == 1 and ')' or '))')155156 # otherwise we create a format string as this is faster in that case157 else:158 format = []159 arguments = []160161 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)167168 self.writeline('yield ')169 self.write(repr(concat(format)) + ' % (')170 self.indent()171172 for argument in arguments:173 self.newline(argument)174 close = 0175176 if finalize is not None:177 self.write('environment.finalize(')178179 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, ')185186 close += 1187188 self.visit(argument, frame)189 self.write(')' * close + ', ')190191 self.outdent()192 self.writeline(')')193194 if outdent_later:195 self.outdent()196197198class 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)207208 try:209 return native_concat(self.root_render_func(self.new_context(vars)))210 except Exception:211 exc_info = sys.exc_info()212213 return self.environment.handle_exception(exc_info, True)214215216class NativeEnvironment(Environment):217 """An environment that renders templates to native Python types."""218219 code_generator_class = NativeCodeGenerator220 template_class = NativeTemplate
added:tests/test_nativetypes.py+110 added
1import pytest23from jinja2._compat import text_type4from jinja2.exceptions import UndefinedError5from jinja2.nativetypes import NativeEnvironment6from jinja2.runtime import Undefined789@pytest.fixture10def env():11 return NativeEnvironment()121314class TestNativeEnvironment(object):15 def test_is_defined_native_return(self, env):16 t = env.from_string('{{ missing is defined }}')17 assert not t.render()1819 def test_undefined_native_return(self, env):20 t = env.from_string('{{ missing }}')21 assert isinstance(t.render(), Undefined)2223 def test_adding_undefined_native_return(self, env):24 t = env.from_string('{{ 3 + missing }}')2526 with pytest.raises(UndefinedError):27 t.render()2829 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 == 33435 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']4041 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']"4647 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'5253 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 == 12345859 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 == 16465 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 True7071 t = env.from_string("{{ boolval }}")72 result = t.render(boolval=False)73 assert isinstance(result, bool)74 assert result is False7576 t = env.from_string("{{ 1 == 1 }}")77 result = t.render()78 assert isinstance(result, bool)79 assert result is True8081 t = env.from_string("{{ 2 + 2 == 5 }}")82 result = t.render()83 assert isinstance(result, bool)84 assert result is False8586 t = env.from_string("{{ None == None }}")87 result = t.render()88 assert isinstance(result, bool)89 assert result is True9091 t = env.from_string("{{ '' == None }}")92 result = t.render()93 assert isinstance(result, bool)94 assert result is False9596 def test_variable_dunder(self, env):97 t = env.from_string("{{ x.__class__ }}")98 result = t.render(x=True)99 assert isinstance(result, type)100101 def test_constant_dunder(self, env):102 t = env.from_string("{{ true.__class__ }}")103 result = t.render()104 assert isinstance(result, type)105106 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 lines
29- 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`_)3637.. _#469: https://github.com/pallets/jinja/pull/46938.. _#475: https://github.com/pallets/jinja/pull/47539.. _#478: https://github.com/pallets/jinja/pull/478
1 unmodified line
41.. _#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/7084647Version 2.9.748-------------49
519 unmodified lines