Skip to content
Myr

Fixed URI encoding of reserved characters (Issue #369).

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

Previously, util.requote_path would unquote and requote all characters, causing reserved characters to become encoded (changing the semantics of the URI). Now, it has special code for unquoting just the unreserved characters, then quotes only illegal characters. This ensures that illegal characters are fixed, and URIs are normalised, but reserved characters do not erroneously become quoted. Test case test_session_with_escaped_url now passes.

authored by Matt Giuca · committed by Matt Giuca · parent c0763bb · Browse files · 1 file+27 added−1 removed
This commit

State

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

Diff stats

1 file+27 added−1 removed

  • other:+27 added−1 removed

1 file+27 added−1 removed

modified:requests/utils.py+27 added-1 removed
394 unmodified lines
395 rv = buf + dec.flush()396 if rv:397 yield rv398399# The unreserved URI characters (RFC 3986)400UNRESERVED_SET = frozenset(401 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"402 + "0123456789-._~")403404def unquote_unreserved(uri):405 """Un-escape any percent-escape sequences in a URI that are unreserved406 characters.407 This leaves all reserved, illegal and non-ASCII bytes encoded.408 """409 parts = uri.split('%')410 for i in range(1, len(parts)):411 h = parts[i][0:2]412 if len(h) == 2:413 c = chr(int(h, 16))414 if c in UNRESERVED_SET:415 parts[i] = c + parts[i][2:]416 else:417 parts[i] = '%' + parts[i]418 else:419 parts[i] = '%' + parts[i]420 return ''.join(parts)421422def requote_path(path):423 """Re-quote the given URL path component.424425 This function passes the given path through an unquote/quote cycle to426 ensure that it is fully and consistently quoted.427 """428 parts = path.split("/")407 parts = (quote(unquote(part), safe="") for part in parts)429 # Unquote only the unreserved characters430 # Then quote only illegal characters (do not quote reserved, unreserved,431 # or '%')432 parts = (quote(unquote_unreserved(part), safe="!#$%&'()*+,/:;=?@[]~")433 for part in parts)434 return "/".join(parts)