Skip to content
Myr

Add a policy for the ascii literal behavior. Fixes #392

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

authored by Armin Ronacher · committed by Armin Ronacher · parent fa80a0d · Browse files · 7 files+48 added−13 removed
This commit

State

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

Diff stats

7 files+48 added−13 removed

  • tests:+25 added−1 removed
  • other:+23 added−12 removed

7 files+48 added−13 removed

modified:docs/api.rst+10 added
554 unmodified lines
555Example::556557 env.policies['urlize.rel'] = 'nofollow noopener'558559``compiler.ascii_str``:560 This boolean controls on Python 2 if Jinja2 should store ASCII only561 literals as bytestring instead of unicode strings. This used to be562 always enabled for Jinja versions below 2.9 and now can be changed.563 Traditionally it was done this way since some APIs in Python 2 failed564 badly for unicode strings (for instance the datetime strftime API).565 Now however sometimes the inverse is true (for instance str.format).566 If this is set to False then all strings are stored as unicode567 internally.568569``urlize.rel``:570 A string that defines the items for the `rel` attribute of generated571 links with the `urlize` filter. These items are always added. The572 default is `noopener`.
327 unmodified lines
modified:jinja2/compiler.py+1 added-1 removed
1338 unmodified lines
13391340 self.write(ref)13411342 def visit_Const(self, node, frame):1343 val = node.value1343 val = node.as_const(frame.eval_ctx)1344 if isinstance(val, float):1345 self.write(str(val))1346 else:1347 self.write(repr(val))
272 unmodified lines
modified:jinja2/defaults.py+1 added
39 unmodified lines
404142# default policies43DEFAULT_POLICIES = {44 'compiler.ascii_str': True,45 'urlize.rel': 'noopener',46 'urlize.target': None,47 'json.dumps_function': None,48 'json.dumps_kwargs': {'sort_keys': True},
5 unmodified lines
modified:jinja2/lexer.py-9 removed
572 unmodified lines
573 .decode('unicode-escape')574 except Exception as e:575 msg = str(e).split(':')[-1].strip()576 raise TemplateSyntaxError(msg, lineno, name, filename)577 # if we can express it as bytestring (ascii only)578 # we do that for support of semi broken APIs579 # as datetime.datetime.strftime. On python 3 this580 # call becomes a noop thanks to 2to3581 if PY2:582 try:583 value = value.encode('ascii')584 except UnicodeError:585 pass577 elif token == 'integer':578 value = int(value)579 elif token == 'float':580 value = float(value)
145 unmodified lines
modified:jinja2/nodes.py+9 added-2 removed
15 unmodified lines
16import operator1718from collections import deque19from jinja2.utils import Markup20from jinja2._compat import izip, with_metaclass, text_type20from jinja2._compat import izip, with_metaclass, text_type, PY2212223#: the types we support for context functions24_context_function_types = (types.FunctionType, types.MethodType)
444 unmodified lines
469 """470 fields = ('value',)471472 def as_const(self, eval_ctx=None):473 return self.value473 rv = self.value474 if PY2 and type(rv) is text_type and \475 self.environment.policies['compiler.ascii_str']:476 try:477 rv = rv.encode('ascii')478 except UnicodeError:479 pass480 return rv481482 @classmethod483 def from_untrusted(cls, value, lineno=None, environment=None):484 """Return a const object if the value is representable as
446 unmodified lines
modified:tests/test_features.py+25 added-1 removed
1import sys2import pytest34from jinja2 import Template4from jinja2 import Template, Environment, contextfilter567@pytest.mark.skipif(sys.version_info < (3, 5),8 reason='Requires 3.5 or later')
4 unmodified lines
1314 t = Template('a{{ bad.bar() }}b')15 with pytest.raises(RuntimeError):16 t.render(bad=X())171819@pytest.mark.skipif(sys.version_info[0] > 2,20 reason='Feature only supported on 2.x')21def test_ascii_str():22 @contextfilter23 def assert_func(context, value):24 assert type(value) is context['expected_type']2526 env = Environment()27 env.filters['assert'] = assert_func2829 env.policies['compiler.ascii_str'] = False30 t = env.from_string('{{ "foo"|assert }}')31 t.render(expected_type=unicode)3233 env.policies['compiler.ascii_str'] = True34 t = env.from_string('{{ "foo"|assert }}')35 t.render(expected_type=str)3637 for val in True, False:38 env.policies['compiler.ascii_str'] = val39 t = env.from_string(u'{{ "\N{SNOWMAN}"|assert }}')40 t.render(expected_type=unicode)
modified:CHANGES+2 added
26 unmodified lines
27 autoescaping information at call time instead of macro define time.28- Ported a modified version of the `tojson` filter from Flask to Jinja229 and hooked it up with the new policy framework.30- Block sets are now marked `safe` by default.31- On Python 2 the asciification of ASCII strings can now be disabled with32 the `compiler.ascii_str` policy.3334Version 2.8.235-------------36
381 unmodified lines