Skip to content
Myr

clarify quoting behavior of urlencode filter

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 77aa538 · Browse files · 3 files+61 added−38 removed
This commit

State

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

Diff stats

3 files+61 added−38 removed

  • tests:+17 added−12 removed
  • other:+44 added−26 removed

3 files+61 added−38 removed

modified:jinja2/filters.py+24 added-15 removed
17 unmodified lines
18from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \19 unicode_urlencode, htmlsafe_json_dumps20from jinja2.runtime import Undefined21from jinja2.exceptions import FilterArgumentError22from jinja2._compat import imap, string_types, text_type, iteritems, PY222from jinja2._compat import imap, string_types, text_type, iteritems, abc232425_word_re = re.compile(r'\w+', re.UNICODE)26_word_beginning_split_re = re.compile(r'([-\s\(\{\[\<]+)', re.UNICODE)
101 unmodified lines
128 return escape(text_type(value))129130131def do_urlencode(value):132 """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both133 dictionaries and regular strings as well as pairwise iterables.132 """Quote data for use in a URL path or query using UTF-8.133134 Basic wrapper around :func:`urllib.parse.quote` when given a135 string, or :func:`urllib.parse.urlencode` for a dict or iterable.136137 :param value: Data to quote. A string will be quoted directly. A138 dict or iterable of ``(key, value)`` pairs will be joined as a139 query string.140141 When given a string, "/" is not quoted. HTTP servers treat "/" and142 "%2F" equivalently in paths. If you need quoted slashes, use the143 ``|replace("/", "%2F")`` filter.144145 .. versionadded:: 2.7146 """137 itemiter = None138 if isinstance(value, dict):139 itemiter = iteritems(value)140 elif not isinstance(value, string_types):141 try:142 itemiter = iter(value)143 except TypeError:144 pass145 if itemiter is None:147 if isinstance(value, string_types) or not isinstance(value, abc.Iterable):148 return unicode_urlencode(value)147 return u'&'.join(unicode_urlencode(k) + '=' +148 unicode_urlencode(v, for_qs=True)149 for k, v in itemiter)149150 if isinstance(value, dict):151 items = iteritems(value)152 else:153 items = iter(value)154155 return u"&".join(156 "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))157 for k, v in items158 )159160161@evalcontextfilter162def do_replace(eval_ctx, s, old, new, count=None):163 """Return a copy of the value with all occurrences of a substring164 replaced with a new one. The first argument is the substring
1197 unmodified lines
modified:jinja2/utils.py+20 added-11 removed
12 unmodified lines
13import json14import warnings15from collections import deque16from threading import Lock17from jinja2._compat import text_type, string_types, implements_iterator, \18 url_quote, abc17from jinja2._compat import text_type, string_types, url_quote, abc181920_word_split_re = re.compile(r'(\s+)')21_punctuation_re = re.compile(
258 unmodified lines
280 return u'\n\n'.join(result)281 return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))282283285def unicode_urlencode(obj, charset='utf-8', for_qs=False):286 """URL escapes a single bytestring or unicode string with the287 given charset if applicable to URL safe quoting under all rules288 that need to be considered under all supported Python versions.284def unicode_urlencode(obj, charset="utf-8", for_qs=False):285 """Quote a string for use in a URL using the given charset.286290 If non strings are provided they are converted to their unicode291 representation first.287 This function is misnamed, it is a wrapper around288 :func:`urllib.parse.quote`.289290 :param obj: String or bytes to quote. Other types are converted to291 string then encoded to bytes using the given charset.292 :param charset: Encode text to bytes using this charset.293 :param for_qs: Quote "/" and use "+" for spaces.294 """295 if not isinstance(obj, string_types):296 obj = text_type(obj)297298 if isinstance(obj, text_type):299 obj = obj.encode(charset)297 safe = not for_qs and b'/' or b''298 rv = text_type(url_quote(obj, safe))300301 safe = b"" if for_qs else b"/"302 rv = url_quote(obj, safe)303304 if not isinstance(rv, text_type):305 rv = rv.decode("utf-8")306307 if for_qs:300 rv = rv.replace('%20', '+')308 rv = rv.replace("%20", "+")309310 return rv311312313class LRUCache(object):
365 unmodified lines
modified:tests/test_filters.py+17 added-12 removed
594 unmodified lines
595 assert tmpl.render() == '<div>foo</div>'596 tmpl = env.from_string('{{ "<div>foo</div>" }}')597 assert tmpl.render() == '&lt;div&gt;foo&lt;/div&gt;'598599 def test_urlencode(self, env):600 env = Environment(autoescape=True)601 tmpl = env.from_string('{{ "Hello, world!"|urlencode }}')602 assert tmpl.render() == 'Hello%2C%20world%21'603 tmpl = env.from_string('{{ o|urlencode }}')604 assert tmpl.render(o=u"Hello, world\u203d") \605 == "Hello%2C%20world%E2%80%BD"606 assert tmpl.render(o=(("f", 1),)) == "f=1"607 assert tmpl.render(o=(('f', 1), ("z", 2))) == "f=1&amp;z=2"608 assert tmpl.render(o=((u"\u203d", 1),)) == "%E2%80%BD=1"609 assert tmpl.render(o={u"\u203d": 1}) == "%E2%80%BD=1"610 assert tmpl.render(o={0: 1}) == "0=1"599 @pytest.mark.parametrize(600 ("value", "expect"),601 [602 ("Hello, world!", "Hello%2C%20world%21"),603 (u"Hello, world\u203d", "Hello%2C%20world%E2%80%BD"),604 ({"f": 1}, "f=1"),605 ([('f', 1), ("z", 2)], "f=1&amp;z=2"),606 ({u"\u203d": 1}, "%E2%80%BD=1"),607 ({0: 1}, "0=1"),608 ([("a b/c", "a b/c")], "a+b%2Fc=a+b%2Fc"),609 ("a b/c", "a%20b/c")610 ],611 )612 def test_urlencode(self, value, expect):613 e = Environment(autoescape=True)614 t = e.from_string("{{ value|urlencode }}")615 assert t.render(value=value) == expect616617 def test_simple_map(self, env):618 env = Environment()619 tmpl = env.from_string('{{ ["1", "2", "3"]|map("int")|sum }}')
151 unmodified lines