utils.py
This file
Path
httpcore/utils.py
91 lines · 2.7 KiB · Python
Last changed by
Add response.text and response.encodingTom Christiebefore adoptiond8df61b
History of this fileTake it
Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 1why, one step back1import codecsFinessing interfaceTom Christiebefore adoptiond7619a9
line 2why, one step back2import httpMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 3–57why, one step back3import typing4from urllib.parse import quote56from .exceptions import InvalidURL78# The unreserved URI characters (RFC 3986)9UNRESERVED_SET = frozenset(10 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"11)121314def unquote_unreserved(uri: str) -> str:15 """16 Un-escape any percent-escape sequences in a URI that are unreserved17 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.18 """19 parts = uri.split("%")20 for i in range(1, len(parts)):21 h = parts[i][0:2]22 if len(h) == 2 and h.isalnum():23 try:24 c = chr(int(h, 16))25 except ValueError:26 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)2728 if c in UNRESERVED_SET:29 parts[i] = c + parts[i][2:]30 else:31 parts[i] = "%" + parts[i]32 else:33 parts[i] = "%" + parts[i]34 return "".join(parts)353637def requote_uri(uri: str) -> str:38 """39 Re-quote the given URI.4041 This function passes the given URI through an unquote/quote cycle to42 ensure that it is fully and consistently quoted.43 """44 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"45 safe_without_percent = "!#$&'()*+,/:;=?@[]~"46 try:47 # Unquote only the unreserved characters48 # Then quote only illegal characters (do not quote reserved,49 # unreserved, or '%')50 return quote(unquote_unreserved(uri), safe=safe_with_percent)51 except InvalidURL:52 # We couldn't unquote the given URI, so let's try quoting it, but53 # there may be unquoted '%'s in the URI. We need to make sure they're54 # properly quoted so they do not cause issues elsewhere.55 return quote(uri, safe=safe_without_percent)5657Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 58why, one step back58def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 59–63why, one step back59 """60 Coerce str/bytes into a strictly byte-wise HTTP header key.61 """62 if isinstance(value, bytes):63 return value.lower()Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 64why, one step back64 return value.encode(encoding or "ascii").lower()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 65–66why, one step back6566Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 67why, one step back67def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 68–72why, one step back68 """69 Coerce str/bytes into a strictly byte-wise HTTP header value.70 """71 if isinstance(value, bytes):72 return valueRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 73why, one step back73 return value.encode(encoding or "ascii")Finessing interfaceTom Christiebefore adoptiond7619a9
lines 74–83why, one step back747576def get_reason_phrase(status_code: int) -> str:77 """78 Return an HTTP reason phrase, eg. "OK" for 200, or "Not Found" for 404.79 """80 try:81 return http.HTTPStatus(status_code).phrase82 except ValueError as exc:83 return ""Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 84–91why, one step back848586def is_known_encoding(encoding: str) -> bool:87 try:88 codecs.lookup(encoding)89 except LookupError:90 return False91 return True