Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions Lib/test/test_urlparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1590,6 +1590,80 @@ def test_quote_errors(self):
encoding='utf-8')
self.assertRaises(TypeError, urllib.parse.quote, b'foo', errors='strict')

def test_quote_ascii_fastpath(self):
all_ascii = ''.join(chr(i) for i in range(128))
all_ascii_bytes = bytes(range(128))

# Verify quote() and quote_plus() match quote_from_bytes() across all
# 128 ASCII characters and custom safe values.
for safe in ('/', '', ' ', '+', ' /?=&', '~_-.'):
expected_quote = urllib.parse.quote_from_bytes(all_ascii_bytes, safe)
self.assertEqual(urllib.parse.quote(all_ascii, safe=safe),
expected_quote)

expected_plus = urllib.parse.quote_from_bytes(
all_ascii_bytes, safe + ' '
).replace(' ', '+')
self.assertEqual(urllib.parse.quote_plus(all_ascii, safe=safe),
expected_plus)

# Every individual ASCII char as safe
for i in range(128):
ch = chr(i)
expected = urllib.parse.quote_from_bytes(all_ascii_bytes, ch)
self.assertEqual(urllib.parse.quote(all_ascii, safe=ch), expected)
expected_plus = urllib.parse.quote_from_bytes(
all_ascii_bytes, ch + ' '
).replace(' ', '+')
self.assertEqual(urllib.parse.quote_plus(all_ascii, safe=ch),
expected_plus)

# safe=' ' in quote_plus still encodes spaces as '+'
self.assertEqual(urllib.parse.quote_plus('a b+c', safe=' '), 'a+b%2Bc')
self.assertEqual(urllib.parse.quote_plus('a b+c', safe='+'), 'a+b+c')

# Non-ASCII safe characters are ignored
self.assertEqual(urllib.parse.quote('a/b c', safe='é/'), 'a/b%20c')
self.assertEqual(urllib.parse.quote_plus('a/b c', safe='é/'), 'a/b+c')

# Non-ASCII string fallback
self.assertEqual(urllib.parse.quote('café /a'), 'caf%C3%A9%20/a')
self.assertEqual(urllib.parse.quote_plus('café /a'), 'caf%C3%A9+%2Fa')

# Encodings: ASCII-compatible and non-ASCII-compatible
for enc in (None, 'utf-8', 'ascii', 'latin-1'):
self.assertEqual(urllib.parse.quote('a b/c', encoding=enc),
'a%20b/c')
self.assertEqual(urllib.parse.quote_plus('a b/c', encoding=enc),
'a+b%2Fc')
self.assertEqual(
urllib.parse.quote('abc', encoding='utf-16'),
urllib.parse.quote_from_bytes('abc'.encode('utf-16'), '/'),
)
self.assertEqual(
urllib.parse.quote_plus('a b', encoding='utf-16'),
urllib.parse.quote_from_bytes('a b'.encode('utf-16'), ' ').replace(' ', '+'),
)

# bytes inputs and bytes safe
self.assertEqual(urllib.parse.quote(b'a b/c'), 'a%20b/c')
self.assertEqual(urllib.parse.quote('a b/c', safe=b'/'), 'a%20b/c')
self.assertEqual(urllib.parse.quote_plus(b'a b/c'), 'a+b%2Fc')
self.assertEqual(urllib.parse.quote_plus('a b/c', safe=b'/'), 'a+b/c')

def test_quote_str_subclass(self):
class SubStr(str):
pass

empty = SubStr('')
self.assertIs(urllib.parse.quote(empty), empty)
self.assertIs(urllib.parse.quote_plus(empty), empty)

for s in (SubStr('abc'), SubStr('a b/c')):
self.assertEqual(urllib.parse.quote(s), urllib.parse.quote(str(s)))
self.assertEqual(urllib.parse.quote_plus(s),
urllib.parse.quote_plus(str(s)))

def test_issue14072(self):
p1 = urllib.parse.urlsplit('tel:+31-641044153')
self.assertEqual(p1.scheme, 'tel')
Expand Down Expand Up @@ -1710,7 +1784,17 @@ def test_Quoter_repr(self):
self.assertIn('Quoter', repr(quoter))

def test_clear_cache_for_code_coverage(self):
urllib.parse.quote('a b/c')
urllib.parse.quote('a b/c', safe='')
urllib.parse.quote('a b/c', safe=':')
urllib.parse.quote_plus('a b/c')
urllib.parse.quote_plus('a b/c', safe=':')
self.assertGreater(urllib.parse._str_quoter.cache_info().currsize, 0)
urllib.parse.clear_cache()
self.assertEqual(urllib.parse._str_quoter.cache_info().currsize, 0)
# Re-populating after clear_cache works identically
self.assertEqual(urllib.parse.quote('a b/c'), 'a%20b/c')
self.assertEqual(urllib.parse.quote_plus('a b/c'), 'a+b%2Fc')

def test_urllib_parse_getattr_failure(self):
"""Test that urllib.parse.__getattr__() fails correctly."""
Expand Down
32 changes: 32 additions & 0 deletions Lib/urllib/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ def clear_cache():
"""Clear internal performance caches. Undocumented; some tests want it."""
urlsplit.cache_clear()
_byte_quoter_factory.cache_clear()
_str_quoter.cache_clear()

# Helpers for bytes handling
# We deliberately require applications that
Expand Down Expand Up @@ -1018,6 +1019,33 @@ def unquote_plus(string, encoding='utf-8', errors='replace'):
_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)


_ALWAYS_SAFE_STR = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789'
'_.-~')
_ASCII_ENCODINGS = (None, 'utf-8', 'ascii', 'latin-1')

@functools.lru_cache
def _str_quoter(safe, plus=False):
safe_set = set(_ALWAYS_SAFE_STR) | set(safe)
if plus:
safe_set.discard(' ')
table = {b: f'%{b:02X}' for b in range(128) if chr(b) not in safe_set}
if plus:
table[32] = '+'
safe_chars = ''.join(c for c in safe_set if ord(c) < 128)
return safe_chars, table

def _quote_ascii(string, safe, encoding, plus=False):
if (isinstance(string, str) and string.isascii() and
isinstance(safe, str) and encoding in _ASCII_ENCODINGS):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see that the encoding needs to be ascii. Problem is that encoding can be lowercased, or without dashes. I now wonder whether we really need this as this makes the check more complex.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can drop _ASCII_ENCODINGS and just check if encoding is None to cover the default path for quote()/quote_plus()/urlencode(). It would still offer speedups

safe_chars, table = _str_quoter(safe, plus)
if not string.rstrip(safe_chars):
return string
return string.translate(table)
return None


class _Quoter(dict):
"""A mapping from bytes numbers (in range(0,256)) to strings.

Expand Down Expand Up @@ -1081,6 +1109,8 @@ def quote(string, safe='/', encoding=None, errors=None):
if isinstance(string, str):
if not string:
return string
if (res := _quote_ascii(string, safe, encoding)) is not None:
return res
if encoding is None:
encoding = 'utf-8'
if errors is None:
Expand All @@ -1098,6 +1128,8 @@ def quote_plus(string, safe='', encoding=None, errors=None):
HTML form values. Plus signs in the original string are escaped unless
they are included in safe. It also does not have safe default to '/'.
"""
if string and (res := _quote_ascii(string, safe, encoding, plus=True)) is not None:
return res
# Check if ' ' in string, where string may either be a str or bytes. If
# there are no spaces, the regular quote will produce the right answer.
if ((isinstance(string, str) and ' ' not in string) or
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up :func:`urllib.parse.quote`, :func:`urllib.parse.quote_plus`, and
:func:`urllib.parse.urlencode` for ASCII :class:`str` inputs.
Loading