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
Provenance
- Commit
028f058- Tree
c2fd3eb- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fa80a0d
7 files changed+48 added−13 removed
modified:docs/api.rst+10 added
554 unmodified lines555 Example::556 557 env.policies['urlize.rel'] = 'nofollow noopener'558 559+``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.568+569 ``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 linesmodified:jinja2/compiler.py+1 added-1 removed
1338 unmodified lines1339 1340 self.write(ref)1341 1342 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 linesmodified:jinja2/defaults.py+1 added
39 unmodified lines40 41 42 # default policies43 DEFAULT_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 linesmodified:jinja2/lexer.py-9 removed
572 unmodified lines573 .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 linesmodified:jinja2/nodes.py+9 added-2 removed
15 unmodified lines16 import operator17 18 from collections import deque19 from jinja2.utils import Markup20-from jinja2._compat import izip, with_metaclass, text_type20+from jinja2._compat import izip, with_metaclass, text_type, PY221 22 23 #: the types we support for context functions24 _context_function_types = (types.FunctionType, types.MethodType)444 unmodified lines469 """470 fields = ('value',)471 472 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 rv481 482 @classmethod483 def from_untrusted(cls, value, lineno=None, environment=None):484 """Return a const object if the value is representable as446 unmodified linesmodified:tests/test_features.py+25 added-1 removed
1 import sys2 import pytest3 4-from jinja2 import Template4+from jinja2 import Template, Environment, contextfilter5 6 7 @pytest.mark.skipif(sys.version_info < (3, 5),8 reason='Requires 3.5 or later')4 unmodified lines13 14 t = Template('a{{ bad.bar() }}b')15 with pytest.raises(RuntimeError):16 t.render(bad=X())17+18+19+@pytest.mark.skipif(sys.version_info[0] > 2,20+ reason='Feature only supported on 2.x')21+def test_ascii_str():22+ @contextfilter23+ def assert_func(context, value):24+ assert type(value) is context['expected_type']25+26+ env = Environment()27+ env.filters['assert'] = assert_func28+29+ env.policies['compiler.ascii_str'] = False30+ t = env.from_string('{{ "foo"|assert }}')31+ t.render(expected_type=unicode)32+33+ env.policies['compiler.ascii_str'] = True34+ t = env.from_string('{{ "foo"|assert }}')35+ t.render(expected_type=str)36+37+ 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 lines27 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.33 34 Version 2.8.235 -------------36 381 unmodified lines