Skip to content
Myr

utils.py

This file

Path

httpcore/utils.py

82 lines · 2.5 KiB · Python

Last changed by

Finessing interfaceTom Christiebefore adoptiond7619a9

History of this file

Take it

1import http2import typing3from urllib.parse import quote45from .exceptions import InvalidURL67# The unreserved URI characters (RFC 3986)8UNRESERVED_SET = frozenset(9    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"10)111213def unquote_unreserved(uri: str) -> str:14    """15    Un-escape any percent-escape sequences in a URI that are unreserved16    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.17    """18    parts = uri.split("%")19    for i in range(1, len(parts)):20        h = parts[i][0:2]21        if len(h) == 2 and h.isalnum():22            try:23                c = chr(int(h, 16))24            except ValueError:25                raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)2627            if c in UNRESERVED_SET:28                parts[i] = c + parts[i][2:]29            else:30                parts[i] = "%" + parts[i]31        else:32            parts[i] = "%" + parts[i]33    return "".join(parts)343536def requote_uri(uri: str) -> str:37    """38    Re-quote the given URI.3940    This function passes the given URI through an unquote/quote cycle to41    ensure that it is fully and consistently quoted.42    """43    safe_with_percent = "!#$%&'()*+,/:;=?@[]~"44    safe_without_percent = "!#$&'()*+,/:;=?@[]~"45    try:46        # Unquote only the unreserved characters47        # Then quote only illegal characters (do not quote reserved,48        # unreserved, or '%')49        return quote(unquote_unreserved(uri), safe=safe_with_percent)50    except InvalidURL:51        # We couldn't unquote the given URI, so let's try quoting it, but52        # there may be unquoted '%'s in the URI. We need to make sure they're53        # properly quoted so they do not cause issues elsewhere.54        return quote(uri, safe=safe_without_percent)555657def normalize_header_key(value: typing.AnyStr) -> bytes:58    """59    Coerce str/bytes into a strictly byte-wise HTTP header key.60    """61    if isinstance(value, bytes):62        return value.lower()63    return value.encode("latin-1").lower()646566def normalize_header_value(value: typing.AnyStr) -> bytes:67    """68    Coerce str/bytes into a strictly byte-wise HTTP header value.69    """70    if isinstance(value, bytes):71        return value72    return value.encode("latin-1")737475def get_reason_phrase(status_code: int) -> str:76    """77    Return an HTTP reason phrase, eg. "OK" for 200, or "Not Found" for 404.78    """79    try:80        return http.HTTPStatus(status_code).phrase81    except ValueError as exc:82        return ""