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
Provenance
- Commit
d988c13- Tree
a7a3be3- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
77aa538
3 files changed+61 added−38 removed
modified:jinja2/filters.py+24 added-15 removed
17 unmodified lines18 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \19 unicode_urlencode, htmlsafe_json_dumps20 from jinja2.runtime import Undefined21 from jinja2.exceptions import FilterArgumentError22-from jinja2._compat import imap, string_types, text_type, iteritems, PY222+from jinja2._compat import imap, string_types, text_type, iteritems, abc23 24 25 _word_re = re.compile(r'\w+', re.UNICODE)26 _word_beginning_split_re = re.compile(r'([-\s\(\{\[\<]+)', re.UNICODE)101 unmodified lines128 return escape(text_type(value))129 130 131 def 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.133 134+ Basic wrapper around :func:`urllib.parse.quote` when given a135+ string, or :func:`urllib.parse.urlencode` for a dict or iterable.136+137+ :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.140+141+ 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.144+145 .. 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)149 150+ if isinstance(value, dict):151+ items = iteritems(value)152+ else:153+ items = iter(value)154 155+ return u"&".join(156+ "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))157+ for k, v in items158+ )159+160+161 @evalcontextfilter162 def 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 substring1197 unmodified linesmodified:jinja2/utils.py+20 added-11 removed
12 unmodified lines13 import json14 import warnings15 from collections import deque16 from threading import Lock17-from jinja2._compat import text_type, string_types, implements_iterator, \18- url_quote, abc17+from jinja2._compat import text_type, string_types, url_quote, abc18 19 20 _word_split_re = re.compile(r'(\s+)')21 _punctuation_re = re.compile(258 unmodified lines280 return u'\n\n'.join(result)281 return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))282 283 285-def 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.284+def unicode_urlencode(obj, charset="utf-8", for_qs=False):285+ """Quote a string for use in a URL using the given charset.286 290- 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`.289+290+ :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)297+298 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))300+301+ safe = b"" if for_qs else b"/"302+ rv = url_quote(obj, safe)303+304+ if not isinstance(rv, text_type):305+ rv = rv.decode("utf-8")306+307 if for_qs:300- rv = rv.replace('%20', '+')308+ rv = rv.replace("%20", "+")309+310 return rv311 312 313 class LRUCache(object):365 unmodified linesmodified:tests/test_filters.py+17 added-12 removed
594 unmodified lines595 assert tmpl.render() == '<div>foo</div>'596 tmpl = env.from_string('{{ "<div>foo</div>" }}')597 assert tmpl.render() == '<div>foo</div>'598 599- 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&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&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) == expect616 617 def test_simple_map(self, env):618 env = Environment()619 tmpl = env.from_string('{{ ["1", "2", "3"]|map("int")|sum }}')151 unmodified lines