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
Provenance
- Commit
6029341- Tree
cefc4b6- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
148a191
13 files changed+56 added−117 removed
modified:src/jinja2/asyncfilters.py+1 added-2 removed
144 unmodified lines145 "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 linesmodified:src/jinja2/asyncsupport.py+1 added-3 removed
1 # -*- coding: utf-8 -*-2-"""The code for async support. Importing this patches Jinja on supported3-Python versions.4-"""2+"""The code for async support. Importing this patches Jinja."""3 import asyncio4 import inspect5 from functools import update_wrapper6 244 unmodified linesmodified:src/jinja2/compiler.py+1 added
679 unmodified lines680 eval_ctx = EvalContext(self.environment, self.name)681 682 from .runtime import exported683 684+ self.writeline("from __future__ import generator_stop") # Python < 3.7685 self.writeline("from jinja2.runtime import " + ", ".join(exported))686 687 if self.environment.is_async:688 self.writeline(1110 unmodified linesmodified:src/jinja2/debug.py+4 added-9 removed
21 unmodified lines22 23 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 exc_value.source = source26-27- 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- pass33-29 # 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.lineno82 unmodified lines115 116 for attr in (117 "argcount",118 "posonlyargcount", # Python 3.8124- "kwonlyargcount", # Python 3119+ "kwonlyargcount",120 "nlocals",121 "stacksize",122 "flags",123 "code", # codestring141 unmodified linesmodified:src/jinja2/environment.py+6 added-8 removed
245 unmodified lines246 247 See :ref:`bytecode-cache` for more information.248 249 `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 """253 254 #: if this environment is sandboxed. Modifying this variable won't make255 #: the environment sandboxed though. For a real sandboxed environment212 unmodified lines468 469 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.473 475- 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.477 478 .. versionadded:: 2.7479 """480 func = self.filters.get(name)835 unmodified linesmodified:src/jinja2/filters.py+5 added-9 removed
562 unmodified lines563 return "%.1f %s" % ((base * bytes / unit), prefix)564 return "%.1f %s" % ((base * bytes / unit), prefix)565 566 567-def do_pprint(value, verbose=False):568- """Pretty print a variable. Useful for debugging.567+def do_pprint(value):568+ """Pretty print a variable. Useful for debugging."""569+ return pformat(value)570 570- 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)571 575-572 @evalcontextfilter573 def do_urlize(574 eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None575 ):14 unmodified lines590 .. sourcecode:: jinja591 592 {{ mytext|urlize(40, target='_blank') }}593 598- .. 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 linesmodified:src/jinja2/lexer.py+2 added-15 removed
8 unmodified lines9 from collections import deque10 from operator import itemgetter11 from sys import intern12 13+from ._identifier import pattern as name_re14 from .exceptions import TemplateSyntaxError15 from .utils import LRUCache16 17 # cache for the lexers. Exists in order to be able to have multiple20 unmodified lines38 """,39 re.IGNORECASE | re.VERBOSE,40 )41 41-try:42- # check if this Python supports Unicode identifiers43- compile("föö", "<unknown>", "eval")44-except 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 = False48-else: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_re52-53- check_ident = True54-42 # internal the tokens and keep references to them43 TOKEN_ADD = intern("add")44 TOKEN_ASSIGN = intern("assign")45 TOKEN_COLON = intern("colon")572 unmodified lines618 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 linesmodified:src/jinja2/nodes.py+5 added-12 removed
210 unmodified lines211 todo.extend(node.iter_child_nodes())212 return self213 214 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 NotImplemented217 219- def __ne__(self, other):220- return not self.__eq__(other)218+ return tuple(self.iter_fields()) == tuple(other.iter_fields())219 222- # Restore Python 2 hashing behavior on Python 3223- __hash__ = object.__hash__220+ def __hash__(self):221+ return hash(tuple(self.iter_fields()))222 223 def __repr__(self):224 return "%s(%s)" % (225 self.__class__.__name__,420 unmodified lines646 647 if eval_ctx.volatile or self.node is None:648 raise Impossible()649 652- # 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)651 652 if filter_ is None or getattr(filter_, "contextfilter", False) is True:653 raise Impossible()413 unmodified linesmodified:src/jinja2/sandbox.py+3 added-13 removed
2 unmodified lines3 Useful when the template itself comes from an untrusted source.4 """5 import operator6 import types7+from _string import formatter_field_name_split8 from collections import abc9 from collections import deque10 from string import Formatter11 171 unmodified lines183 184 185 def 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.189 190 >>> modifies_known_mutable({}, "clear")191 True192 >>> modifies_known_mutable({}, "keys")231 unmodified lines424 return False425 return not modifies_known_mutable(obj, attr)426 427 429-# This really is not a public API apparently.430-try:431- from _string import formatter_field_name_split432-except ImportError:433-434- def formatter_field_name_split(field_name):435- return field_name._formatter_field_name_split()436-437-428 class SandboxedFormatterMixin(object):429 def __init__(self, env):430 self._env = env431 21 unmodified linesmodified:src/jinja2/utils.py+4 added-10 removed
167 unmodified lines168 name = obj.__class__.__module__ + "." + obj.__class__.__name__169 return "%s object" % name170 171 172-def pformat(obj, verbose=False):173- """Prettyprint an object. Either use the `pretty` library or the174- builtin `pprint`.172+def pformat(obj):173+ """Format an object using :func:`pprint.pformat`.174 """176- try:177- from pretty import pretty175+ from pprint import pformat176 179- return pretty(obj, verbose=verbose)180- except ImportError:181- from pprint import pformat177+ return pformat(obj)178 183- return pformat(obj)179 185-180 def 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) and487 unmodified linesmodified:tests/test_api.py-1 removed
30 unmodified lines31 def test_item_and_attribute(self, env):32 from jinja2.sandbox import SandboxedEnvironment33 34 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 linesmodified:tests/test_ext.py+24 added-32 removed
338 unmodified lines339 def test_extract(self):340 from jinja2.ext import babel_extract341 342 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 lines355 def test_extract_trimmed(self):356 from jinja2.ext import babel_extract357 358 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 lines372 def test_extract_trimmed_option(self):373 from jinja2.ext import babel_extract374 375 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 lines390 def test_comment_extract(self):391 from jinja2.ext import babel_extract392 393 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 linesmodified:tests/test_security.py-3 removed
149 unmodified lines150 assert t.render() == "a42b<foo>"151 152 153 @pytest.mark.sandbox154-@pytest.mark.skipif(155- not hasattr(str, "format_map"), reason="requires str.format_map method"156-)154 class 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