Skip to content
Myr

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 file

Take it

1import codecs2import http3import 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)565758def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:59    """60    Coerce str/bytes into a strictly byte-wise HTTP header key.61    """62    if isinstance(value, bytes):63        return value.lower()64    return value.encode(encoding or "ascii").lower()656667def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:68    """69    Coerce str/bytes into a strictly byte-wise HTTP header value.70    """71    if isinstance(value, bytes):72        return value73    return value.encode(encoding or "ascii")747576def 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 ""848586def is_known_encoding(encoding: str) -> bool:87    try:88        codecs.lookup(encoding)89    except LookupError:90        return False91    return True