Skip to content
Myr

utils.py

This file

Path

httpcore/utils.py

71 lines · 2.2 KiB · Python

Last changed by

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

History of this file

Take it

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 1–71why, one step back
1import typing
2from urllib.parse import quote34from .exceptions import InvalidURL56# The unreserved URI characters (RFC 3986)7UNRESERVED_SET = frozenset(8 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"9)101112def unquote_unreserved(uri: str) -> str:13 """14 Un-escape any percent-escape sequences in a URI that are unreserved15 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.16 """17 parts = uri.split("%")18 for i in range(1, len(parts)):19 h = parts[i][0:2]20 if len(h) == 2 and h.isalnum():21 try:22 c = chr(int(h, 16))23 except ValueError:24 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)2526 if c in UNRESERVED_SET:27 parts[i] = c + parts[i][2:]28 else:29 parts[i] = "%" + parts[i]30 else:31 parts[i] = "%" + parts[i]32 return "".join(parts)333435def requote_uri(uri: str) -> str:36 """37 Re-quote the given URI.3839 This function passes the given URI through an unquote/quote cycle to40 ensure that it is fully and consistently quoted.41 """42 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"43 safe_without_percent = "!#$&'()*+,/:;=?@[]~"44 try:45 # Unquote only the unreserved characters46 # Then quote only illegal characters (do not quote reserved,47 # unreserved, or '%')48 return quote(unquote_unreserved(uri), safe=safe_with_percent)49 except InvalidURL:50 # We couldn't unquote the given URI, so let's try quoting it, but51 # there may be unquoted '%'s in the URI. We need to make sure they're52 # properly quoted so they do not cause issues elsewhere.53 return quote(uri, safe=safe_without_percent)545556def normalize_header_key(value: typing.AnyStr) -> bytes:57 """58 Coerce str/bytes into a strictly byte-wise HTTP header key.59 """60 if isinstance(value, bytes):61 return value.lower()62 return value.encode("latin-1").lower()636465def normalize_header_value(value: typing.AnyStr) -> bytes:66 """67 Coerce str/bytes into a strictly byte-wise HTTP header value.68 """69 if isinstance(value, bytes):70 return value71 return value.encode("latin-1")