Skip to content
Myr

utils.py

This file

Path

httpcore/utils.py

52 lines · 1.7 KiB · Python

Last changed by

Rollin'Tom Christiebefore adoption8a29a0a

History of this file

Take it

Rollin'Tom Christiebefore adoption8a29a0a

lines 1–52why, one step back
1from urllib.parse import quote
23from .exceptions import InvalidURL45# The unreserved URI characters (RFC 3986)6UNRESERVED_SET = frozenset(7 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"8)91011def unquote_unreserved(uri: str) -> str:12 """Un-escape any percent-escape sequences in a URI that are unreserved13 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.14 :rtype: str15 """16 parts = uri.split("%")17 for i in range(1, len(parts)):18 h = parts[i][0:2]19 if len(h) == 2 and h.isalnum():20 try:21 c = chr(int(h, 16))22 except ValueError:23 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)2425 if c in UNRESERVED_SET:26 parts[i] = c + parts[i][2:]27 else:28 parts[i] = "%" + parts[i]29 else:30 parts[i] = "%" + parts[i]31 return "".join(parts)323334def requote_uri(uri: str) -> str:35 """36 Re-quote the given URI.3738 This function passes the given URI through an unquote/quote cycle to39 ensure that it is fully and consistently quoted.40 """41 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"42 safe_without_percent = "!#$&'()*+,/:;=?@[]~"43 try:44 # Unquote only the unreserved characters45 # Then quote only illegal characters (do not quote reserved,46 # unreserved, or '%')47 return quote(unquote_unreserved(uri), safe=safe_with_percent)48 except InvalidURL:49 # We couldn't unquote the given URI, so let's try quoting it, but50 # there may be unquoted '%'s in the URI. We need to make sure they're51 # properly quoted so they do not cause issues elsewhere.52 return quote(uri, safe=safe_without_percent)