Skip to content
Myr

remove more compat code

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

authored by David Lord · committed by David Lord · parent 148a191 · Browse files · 13 files+56 added−117 removed
This commit

State

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

Diff stats

13 files+56 added−117 removed

  • tests:+24 added−36 removed
  • other:+32 added−81 removed

13 files+56 added−117 removed

modified:src/jinja2/asyncfilters.py+1 added-2 removed
144 unmodified lines
145 "first": do_first,146 "groupby": do_groupby,147 "join": do_join,148 "list": do_list,149 # we intentionally do not support do_last because that would be150 # ridiculous149 # we intentionally do not support do_last because it may not be safe in async150 "reject": do_reject,151 "rejectattr": do_rejectattr,152 "map": do_map,153 "select": do_select,
4 unmodified lines
modified:src/jinja2/asyncsupport.py+1 added-3 removed
1# -*- coding: utf-8 -*-2"""The code for async support. Importing this patches Jinja on supported3Python versions.4"""2"""The code for async support. Importing this patches Jinja."""3import asyncio4import inspect5from functools import update_wrapper6
244 unmodified lines
modified:src/jinja2/compiler.py+1 added
679 unmodified lines
680 eval_ctx = EvalContext(self.environment, self.name)681682 from .runtime import exported683684 self.writeline("from __future__ import generator_stop") # Python < 3.7685 self.writeline("from jinja2.runtime import " + ", ".join(exported))686687 if self.environment.is_async:688 self.writeline(
1110 unmodified lines
modified:src/jinja2/debug.py+4 added-9 removed
21 unmodified lines
2223 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 exc_value.source = source2627 try:28 # Remove the old traceback on Python 3, otherwise the frames29 # from the compiler still show up.30 exc_value.with_traceback(None)26 # Remove the old traceback, otherwise the frames from the27 # compiler still show up.28 exc_value.with_traceback(None)31 except AttributeError:32 pass3329 # Outside of runtime, so the frame isn't executing template30 # code, but it still needs to point at the template.31 tb = fake_traceback(32 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
82 unmodified lines
115116 for attr in (117 "argcount",118 "posonlyargcount", # Python 3.8124 "kwonlyargcount", # Python 3119 "kwonlyargcount",120 "nlocals",121 "stacksize",122 "flags",123 "code", # codestring
141 unmodified lines
modified:src/jinja2/environment.py+6 added-8 removed
245 unmodified lines
246247 See :ref:`bytecode-cache` for more information.248249 `enable_async`250 If set to true this enables async template execution which allows251 you to take advantage of newer Python features. This requires252 Python 3.6 or later.250 If set to true this enables async template execution which251 allows using async functions and generators.252 """253254 #: if this environment is sandboxed. Modifying this variable won't make255 #: the environment sandboxed though. For a real sandboxed environment
212 unmodified lines
468469 def call_filter(470 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None471 ):473 """Invokes a filter on a value the same way the compiler does it.472 """Invokes a filter on a value the same way the compiler does.473475 Note that on Python 3 this might return a coroutine in case the476 filter is running from an environment in async mode and the filter477 supports async execution. It's your responsibility to await this478 if needed.474 This might return a coroutine if the filter is running from an475 environment in async mode and the filter supports async476 execution. It's your responsibility to await this if needed.477478 .. versionadded:: 2.7479 """480 func = self.filters.get(name)
835 unmodified lines
modified:src/jinja2/filters.py+5 added-9 removed
562 unmodified lines
563 return "%.1f %s" % ((base * bytes / unit), prefix)564 return "%.1f %s" % ((base * bytes / unit), prefix)565566567def do_pprint(value, verbose=False):568 """Pretty print a variable. Useful for debugging.567def do_pprint(value):568 """Pretty print a variable. Useful for debugging."""569 return pformat(value)570570 With Jinja 1.2 onwards you can pass it a parameter. If this parameter571 is truthy the output will be more verbose (this requires `pretty`)572 """573 return pformat(value, verbose=verbose)571575572@evalcontextfilter573def do_urlize(574 eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None575):
14 unmodified lines
590 .. sourcecode:: jinja591592 {{ mytext|urlize(40, target='_blank') }}593598 .. versionchanged:: 2.8+599 The *target* parameter was added.594 .. versionchanged:: 2.8595 The ``target`` parameter was added.596 """597 policies = eval_ctx.environment.policies598 rel = set((rel or "").split() or [])599 if nofollow:
765 unmodified lines
modified:src/jinja2/lexer.py+2 added-15 removed
8 unmodified lines
9from collections import deque10from operator import itemgetter11from sys import intern1213from ._identifier import pattern as name_re14from .exceptions import TemplateSyntaxError15from .utils import LRUCache1617# cache for the lexers. Exists in order to be able to have multiple
20 unmodified lines
38 """,39 re.IGNORECASE | re.VERBOSE,40)4141try:42 # check if this Python supports Unicode identifiers43 compile("föö", "<unknown>", "eval")44except SyntaxError:45 # Python 2, no Unicode support, use ASCII identifiers46 name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")47 check_ident = False48else:49 # Unicode support, import generated re pattern and set flag to use50 # str.isidentifier to validate during lexing.51 from ._identifier import pattern as name_re5253 check_ident = True5442# internal the tokens and keep references to them43TOKEN_ADD = intern("add")44TOKEN_ASSIGN = intern("assign")45TOKEN_COLON = intern("colon")
572 unmodified lines
618 elif token == "keyword":619 token = value620 elif token == TOKEN_NAME:621 value = str(value)635 if check_ident and not value.isidentifier():622 if not value.isidentifier():623 raise TemplateSyntaxError(624 "Invalid character in identifier", lineno, name, filename625 )626 elif token == TOKEN_STRING:
198 unmodified lines
modified:src/jinja2/nodes.py+5 added-12 removed
210 unmodified lines
211 todo.extend(node.iter_child_nodes())212 return self213214 def __eq__(self, other):215 return type(self) is type(other) and tuple(self.iter_fields()) == tuple(216 other.iter_fields()217 )215 if type(self) is not type(other):216 return NotImplemented217219 def __ne__(self, other):220 return not self.__eq__(other)218 return tuple(self.iter_fields()) == tuple(other.iter_fields())219222 # Restore Python 2 hashing behavior on Python 3223 __hash__ = object.__hash__220 def __hash__(self):221 return hash(tuple(self.iter_fields()))222223 def __repr__(self):224 return "%s(%s)" % (225 self.__class__.__name__,
420 unmodified lines
646647 if eval_ctx.volatile or self.node is None:648 raise Impossible()649652 # we have to be careful here because we call filter_ below.653 # if this variable would be called filter, 2to3 would wrap the654 # call in a list because it is assuming we are talking about the655 # builtin filter function here which no longer returns a list in656 # python 3. because of that, do not rename filter_ to filter!650 filter_ = self.environment.filters.get(self.name)651652 if filter_ is None or getattr(filter_, "contextfilter", False) is True:653 raise Impossible()
413 unmodified lines
modified:src/jinja2/sandbox.py+3 added-13 removed
2 unmodified lines
3Useful when the template itself comes from an untrusted source.4"""5import operator6import types7from _string import formatter_field_name_split8from collections import abc9from collections import deque10from string import Formatter11
171 unmodified lines
183184185def modifies_known_mutable(obj, attr):186 """This function checks if an attribute on a builtin mutable object186 (list, dict, set or deque) would modify it if called. It also supports187 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and188 with Python 2.6 onwards the abstract base classes `MutableSet`,189 `MutableMapping`, and `MutableSequence`.187 (list, dict, set or deque) or the corresponding ABCs would modify it188 if called.189190 >>> modifies_known_mutable({}, "clear")191 True192 >>> modifies_known_mutable({}, "keys")
231 unmodified lines
424 return False425 return not modifies_known_mutable(obj, attr)426427429# This really is not a public API apparently.430try:431 from _string import formatter_field_name_split432except ImportError:433434 def formatter_field_name_split(field_name):435 return field_name._formatter_field_name_split()436437428class SandboxedFormatterMixin(object):429 def __init__(self, env):430 self._env = env431
21 unmodified lines
modified:src/jinja2/utils.py+4 added-10 removed
167 unmodified lines
168 name = obj.__class__.__module__ + "." + obj.__class__.__name__169 return "%s object" % name170171172def pformat(obj, verbose=False):173 """Prettyprint an object. Either use the `pretty` library or the174 builtin `pprint`.172def pformat(obj):173 """Format an object using :func:`pprint.pformat`.174 """176 try:177 from pretty import pretty175 from pprint import pformat176179 return pretty(obj, verbose=verbose)180 except ImportError:181 from pprint import pformat177 return pformat(obj)178183 return pformat(obj)179185180def urlize(text, trim_url_limit=None, rel=None, target=None):181 """Converts any URLs in text into clickable links. Works on http://,182 https:// and www. links. Links can have trailing punctuation (periods,183 commas, close-parens) and leading punctuation (opening parens) and
487 unmodified lines
modified:tests/test_api.py-1 removed
30 unmodified lines
31 def test_item_and_attribute(self, env):32 from jinja2.sandbox import SandboxedEnvironment3334 for env in Environment(), SandboxedEnvironment():35 # the |list is necessary for python335 tmpl = env.from_string("{{ foo.items()|list }}")36 assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"37 tmpl = env.from_string('{{ foo|attr("items")()|list }}')38 assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"
393 unmodified lines
modified:tests/test_ext.py+24 added-32 removed
338 unmodified lines
339 def test_extract(self):340 from jinja2.ext import babel_extract341342 source = BytesIO(343 b"""344 {{ gettext('Hello World') }}345 {% trans %}Hello World{% endtrans %}346 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}347 """344 {{ gettext('Hello World') }}345 {% trans %}Hello World{% endtrans %}346 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}347 """.encode(348 "ascii"349 )348 )350 ) # make python 3 happy349 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [350 (2, "gettext", u"Hello World", []),351 (3, "gettext", u"Hello World", []),352 (4, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),
2 unmodified lines
355 def test_extract_trimmed(self):356 from jinja2.ext import babel_extract357358 source = BytesIO(359 b"""360 {{ gettext(' Hello \n World') }}361 {% trans trimmed %} Hello \n World{% endtrans %}362 {% trans trimmed %}{{ users }} \n user363 {%- pluralize %}{{ users }} \n users{% endtrans %}364 """362 {{ gettext(' Hello \n World') }}363 {% trans trimmed %} Hello \n World{% endtrans %}364 {% trans trimmed %}{{ users }} \n user365 {%- pluralize %}{{ users }} \n users{% endtrans %}366 """.encode(367 "ascii"368 )365 )369 ) # make python 3 happy366 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [367 (2, "gettext", u" Hello \n World", []),368 (4, "gettext", u"Hello World", []),369 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),
2 unmodified lines
372 def test_extract_trimmed_option(self):373 from jinja2.ext import babel_extract374375 source = BytesIO(376 b"""377 {{ gettext(' Hello \n World') }}378 {% trans %} Hello \n World{% endtrans %}379 {% trans %}{{ users }} \n user380 {%- pluralize %}{{ users }} \n users{% endtrans %}381 """381 {{ gettext(' Hello \n World') }}382 {% trans %} Hello \n World{% endtrans %}383 {% trans %}{{ users }} \n user384 {%- pluralize %}{{ users }} \n users{% endtrans %}385 """.encode(386 "ascii"387 )382 )388 ) # make python 3 happy383 opts = {"trimmed": "true"}384 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [385 (2, "gettext", u" Hello \n World", []),386 (4, "gettext", u"Hello World", []),
3 unmodified lines
390 def test_comment_extract(self):391 from jinja2.ext import babel_extract392393 source = BytesIO(394 b"""395 {# trans first #}396 {{ gettext('Hello World') }}397 {% trans %}Hello World{% endtrans %}{# trans second #}398 {#: third #}399 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}400 """401 {# trans first #}402 {{ gettext('Hello World') }}403 {% trans %}Hello World{% endtrans %}{# trans second #}404 {#: third #}405 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}406 """.encode(407 "utf-8"408 )401 )409 ) # make python 3 happy402 assert list(403 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})404 ) == [405 (3, "gettext", u"Hello World", ["first"]),
245 unmodified lines
modified:tests/test_security.py-3 removed
149 unmodified lines
150 assert t.render() == "a42b&lt;foo&gt;"151152153@pytest.mark.sandbox154@pytest.mark.skipif(155 not hasattr(str, "format_map"), reason="requires str.format_map method"156)154class TestStringFormatMap(object):155 def test_basic_format_safety(self):156 env = SandboxedEnvironment()157 t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')
13 unmodified lines