Skip to content
Myr

utils.py

This file

Path

httpx/utils.py

341 lines · 10.5 KiB · Python

Last changed by

Drop MessageLoggerASGIMiddleware. (#573)Tom Christiebefore adoption095b691

History of this file

Take it

1import codecs2import collections3import logging4import netrc5import os6import re7import sys8import typing9from datetime import timedelta10from pathlib import Path11from time import perf_counter12from types import TracebackType13from urllib.request import getproxies1415if typing.TYPE_CHECKING:  # pragma: no cover16    from .models import PrimitiveData17    from .models import URL181920def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:21    """22    Coerce str/bytes into a strictly byte-wise HTTP header key.23    """24    if isinstance(value, bytes):25        return value.lower()26    return value.encode(encoding or "ascii").lower()272829def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:30    """31    Coerce str/bytes into a strictly byte-wise HTTP header value.32    """33    if isinstance(value, bytes):34        return value35    return value.encode(encoding or "ascii")363738def str_query_param(value: "PrimitiveData") -> str:39    """40    Coerce a primitive data type into a string value for query params.4142    Note that we prefer JSON-style 'true'/'false' for boolean values here.43    """44    if value is True:45        return "true"46    elif value is False:47        return "false"48    elif value is None:49        return ""50    return str(value)515253def is_known_encoding(encoding: str) -> bool:54    """55    Return `True` if `encoding` is a known codec.56    """57    try:58        codecs.lookup(encoding)59    except LookupError:60        return False61    return True626364# Null bytes; no need to recreate these on each call to guess_json_utf65_null = "\x00".encode("ascii")  # encoding to ASCII for Python 366_null2 = _null * 267_null3 = _null * 3686970def guess_json_utf(data: bytes) -> typing.Optional[str]:71    # JSON always starts with two ASCII characters, so detection is as72    # easy as counting the nulls and from their location and count73    # determine the encoding. Also detect a BOM, if present.74    sample = data[:4]75    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):76        return "utf-32"  # BOM included77    if sample[:3] == codecs.BOM_UTF8:78        return "utf-8-sig"  # BOM included, MS style (discouraged)79    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):80        return "utf-16"  # BOM included81    nullcount = sample.count(_null)82    if nullcount == 0:83        return "utf-8"84    if nullcount == 2:85        if sample[::2] == _null2:  # 1st and 3rd are null86            return "utf-16-be"87        if sample[1::2] == _null2:  # 2nd and 4th are null88            return "utf-16-le"89        # Did not detect 2 valid UTF-16 ascii-range characters90    if nullcount == 3:91        if sample[:3] == _null3:92            return "utf-32-be"93        if sample[1:] == _null3:94            return "utf-32-le"95        # Did not detect a valid UTF-32 ascii-range character96    return None979899class NetRCInfo:100    def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:101        if files is None:102            files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]103        self.netrc_files = files104105    @property106    def netrc_info(self) -> typing.Optional[netrc.netrc]:107        if not hasattr(self, "_netrc_info"):108            self._netrc_info = None109            for file_path in self.netrc_files:110                expanded_path = Path(file_path).expanduser()111                if expanded_path.is_file():112                    self._netrc_info = netrc.netrc(str(expanded_path))113                    break114        return self._netrc_info115116    def get_credentials(117        self, authority: str118    ) -> typing.Optional[typing.Tuple[str, str]]:119        if self.netrc_info is None:120            return None121122        auth_info = self.netrc_info.authenticators(authority)123        if auth_info is None or auth_info[2] is None:124            return None125        return (auth_info[0], auth_info[2])126127128def get_ca_bundle_from_env() -> typing.Optional[str]:129    if "SSL_CERT_FILE" in os.environ:130        ssl_file = Path(os.environ["SSL_CERT_FILE"])131        if ssl_file.is_file():132            return str(ssl_file)133    if "SSL_CERT_DIR" in os.environ:134        ssl_path = Path(os.environ["SSL_CERT_DIR"])135        if ssl_path.is_dir():136            return str(ssl_path)137    return None138139140def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:141    """142    Returns a list of parsed link headers, for more info see:143    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link144    The generic syntax of those is:145    Link: < uri-reference >; param1=value1; param2="value2"146    So for instance:147    Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'148    would return149        [150            {"url": "http:/.../front.jpeg", "type": "image/jpeg"},151            {"url": "http://.../back.jpeg"},152        ]153    :param value: HTTP Link entity-header field154    :return: list of parsed link headers155    """156    links: typing.List[typing.Dict[str, str]] = []157    replace_chars = " '\""158    value = value.strip(replace_chars)159    if not value:160        return links161    for val in re.split(", *<", value):162        try:163            url, params = val.split(";", 1)164        except ValueError:165            url, params = val, ""166        link = {"url": url.strip("<> '\"")}167        for param in params.split(";"):168            try:169                key, value = param.split("=")170            except ValueError:171                break172            link[key.strip(replace_chars)] = value.strip(replace_chars)173        links.append(link)174    return links175176177SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}178179180def obfuscate_sensitive_headers(181    items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]182) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:183    for k, v in items:184        if to_str(k.lower()) in SENSITIVE_HEADERS:185            v = to_bytes_or_str("[secure]", match_type_of=v)186        yield k, v187188189_LOGGER_INITIALIZED = False190TRACE_LOG_LEVEL = 5191192193class Logger(logging.Logger):194    # Stub for type checkers.195    def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:196        ...  # pragma: nocover197198199def get_logger(name: str) -> Logger:200    """201    Get a `logging.Logger` instance, and optionally202    set up debug logging based on the HTTPX_LOG_LEVEL environment variable.203    """204    global _LOGGER_INITIALIZED205206    if not _LOGGER_INITIALIZED:207        _LOGGER_INITIALIZED = True208        logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")209210        log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()211        if log_level in ("DEBUG", "TRACE"):212            logger = logging.getLogger("httpx")213            logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)214            handler = logging.StreamHandler(sys.stderr)215            handler.setFormatter(216                logging.Formatter(217                    fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",218                    datefmt="%Y-%m-%d %H:%M:%S",219                )220            )221            logger.addHandler(handler)222223    logger = logging.getLogger(name)224225    def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:226        logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)227228    logger.trace = trace  # type: ignore229230    return typing.cast(Logger, logger)231232233def kv_format(**kwargs: typing.Any) -> str:234    """Format arguments into a key=value line.235236    >>> formatkv(x=1, name="Bob")237    "x=1 name='Bob'"238    """239    return " ".join(f"{key}={value!r}" for key, value in kwargs.items())240241242def should_not_be_proxied(url: "URL") -> bool:243    """ Return True if url should not be proxied,244    return False otherwise.245    """246    no_proxy = getproxies().get("no")247    if not no_proxy:248        return False249    no_proxy_list = [host.strip() for host in no_proxy.split(",")]250    for name in no_proxy_list:251        if name == "*":252            return True253        if name:254            name = name.lstrip(".")  # ignore leading dots255            name = re.escape(name)256            pattern = r"(.+\.)?%s$" % name257            if re.match(pattern, url.host, re.I) or re.match(258                pattern, url.authority, re.I259            ):260                return True261    return False262263264def get_environment_proxies() -> typing.Dict[str, str]:265    """Gets proxy information from the environment"""266267    # urllib.request.getproxies() falls back on System268    # Registry and Config for proxies on Windows and macOS.269    # We don't want to propagate non-HTTP proxies into270    # our configuration such as 'TRAVIS_APT_PROXY'.271    supported_proxy_schemes = ("http", "https", "all")272    return {273        key: val274        for key, val in getproxies().items()275        if ("://" in key or key in supported_proxy_schemes)276    }277278279def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:280    return value.encode(encoding) if isinstance(value, str) else value281282283def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:284    return value if isinstance(value, str) else value.decode(encoding)285286287def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:288    return value if isinstance(match_type_of, str) else value.encode()289290291def unquote(value: str) -> str:292    return value[1:-1] if value[0] == value[-1] == '"' else value293294295def flatten_queryparams(296    queryparams: typing.Mapping[297        str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]298    ]299) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:300    """301    Convert a mapping of query params into a flat list of two-tuples302    representing each item.303304    Example:305    >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})306    [("q", "httpx), ("tag", "python"), ("tag", "dev")]307    """308    items = []309310    for k, v in queryparams.items():311        if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):312            for u in v:313                items.append((k, u))314        else:315            items.append((k, typing.cast("PrimitiveData", v)))316317    return items318319320class ElapsedTimer:321    def __init__(self) -> None:322        self.start: float = perf_counter()323        self.end: typing.Optional[float] = None324325    def __enter__(self) -> "ElapsedTimer":326        self.start = perf_counter()327        return self328329    def __exit__(330        self,331        exc_type: typing.Type[BaseException] = None,332        exc_value: BaseException = None,333        traceback: TracebackType = None,334    ) -> None:335        self.end = perf_counter()336337    @property338    def elapsed(self) -> timedelta:339        if self.end is None:340            return timedelta(seconds=perf_counter() - self.start)341        return timedelta(seconds=self.end - self.start)