Skip to content
Myr

utils.py

This file

Path

httpx/utils.py

370 lines · 11.3 KiB · Python

Last changed by

Allow lists in query params (#386)Florimond Mancabefore adoption57ae7ea

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 PrimitiveData171819def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:20    """21    Coerce str/bytes into a strictly byte-wise HTTP header key.22    """23    if isinstance(value, bytes):24        return value.lower()25    return value.encode(encoding or "ascii").lower()262728def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:29    """30    Coerce str/bytes into a strictly byte-wise HTTP header value.31    """32    if isinstance(value, bytes):33        return value34    return value.encode(encoding or "ascii")353637def str_query_param(value: "PrimitiveData") -> str:38    """39    Coerce a primitive data type into a string value for query params.4041    Note that we prefer JSON-style 'true'/'false' for boolean values here.42    """43    if value is True:44        return "true"45    elif value is False:46        return "false"47    elif value is None:48        return ""49    return str(value)505152def is_known_encoding(encoding: str) -> bool:53    """54    Return `True` if `encoding` is a known codec.55    """56    try:57        codecs.lookup(encoding)58    except LookupError:59        return False60    return True616263# Null bytes; no need to recreate these on each call to guess_json_utf64_null = "\x00".encode("ascii")  # encoding to ASCII for Python 365_null2 = _null * 266_null3 = _null * 3676869def guess_json_utf(data: bytes) -> typing.Optional[str]:70    # JSON always starts with two ASCII characters, so detection is as71    # easy as counting the nulls and from their location and count72    # determine the encoding. Also detect a BOM, if present.73    sample = data[:4]74    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):75        return "utf-32"  # BOM included76    if sample[:3] == codecs.BOM_UTF8:77        return "utf-8-sig"  # BOM included, MS style (discouraged)78    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):79        return "utf-16"  # BOM included80    nullcount = sample.count(_null)81    if nullcount == 0:82        return "utf-8"83    if nullcount == 2:84        if sample[::2] == _null2:  # 1st and 3rd are null85            return "utf-16-be"86        if sample[1::2] == _null2:  # 2nd and 4th are null87            return "utf-16-le"88        # Did not detect 2 valid UTF-16 ascii-range characters89    if nullcount == 3:90        if sample[:3] == _null3:91            return "utf-32-be"92        if sample[1:] == _null3:93            return "utf-32-le"94        # Did not detect a valid UTF-32 ascii-range character95    return None969798NETRC_STATIC_FILES = (Path("~/.netrc"), Path("~/_netrc"))99100101def get_netrc_login(host: str) -> typing.Optional[typing.Tuple[str, str, str]]:102    NETRC_FILES = (Path(os.getenv("NETRC", "")),) + NETRC_STATIC_FILES103    netrc_path = None104105    for file_path in NETRC_FILES:106        expanded_path = file_path.expanduser()107        if expanded_path.is_file():108            netrc_path = expanded_path109            break110111    if netrc_path is None:112        return None113114    netrc_info = netrc.netrc(str(netrc_path))115    return netrc_info.authenticators(host)  # type: ignore116117118def get_ca_bundle_from_env() -> typing.Optional[str]:119    if "SSL_CERT_FILE" in os.environ:120        ssl_file = Path(os.environ["SSL_CERT_FILE"])121        if ssl_file.is_file():122            return str(ssl_file)123    if "SSL_CERT_DIR" in os.environ:124        ssl_path = Path(os.environ["SSL_CERT_DIR"])125        if ssl_path.is_dir():126            return str(ssl_path)127    return None128129130def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:131    """132    Returns a list of parsed link headers, for more info see:133    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link134    The generic syntax of those is:135    Link: < uri-reference >; param1=value1; param2="value2"136    So for instance:137    Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'138    would return139        [140            {"url": "http:/.../front.jpeg", "type": "image/jpeg"},141            {"url": "http://.../back.jpeg"},142        ]143    :param value: HTTP Link entity-header field144    :return: list of parsed link headers145    """146    links: typing.List[typing.Dict[str, str]] = []147    replace_chars = " '\""148    value = value.strip(replace_chars)149    if not value:150        return links151    for val in re.split(", *<", value):152        try:153            url, params = val.split(";", 1)154        except ValueError:155            url, params = val, ""156        link = {"url": url.strip("<> '\"")}157        for param in params.split(";"):158            try:159                key, value = param.split("=")160            except ValueError:161                break162            link[key.strip(replace_chars)] = value.strip(replace_chars)163        links.append(link)164    return links165166167SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}168169170def obfuscate_sensitive_headers(171    items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]172) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:173    for k, v in items:174        if to_str(k.lower()) in SENSITIVE_HEADERS:175            v = to_bytes_or_str("[secure]", match_type_of=v)176        yield k, v177178179_LOGGER_INITIALIZED = False180181182def get_logger(name: str) -> logging.Logger:183    """Gets a `logging.Logger` instance and optionally184    sets up debug logging if the user requests it via185    the `HTTPX_DEBUG=1` environment variable.186    """187    global _LOGGER_INITIALIZED188189    if not _LOGGER_INITIALIZED:190        _LOGGER_INITIALIZED = True191        if os.environ.get("HTTPX_DEBUG", "").lower() in ("1", "true"):192            logger = logging.getLogger("httpx")193            logger.setLevel(logging.DEBUG)194            handler = logging.StreamHandler(sys.stderr)195            handler.setFormatter(196                logging.Formatter(197                    fmt="%(asctime)s.%(msecs)03d - %(name)s - %(message)s",198                    datefmt="%H:%M:%S",199                )200            )201            logger.addHandler(handler)202203    return logging.getLogger(name)204205206def kv_format(**kwargs: typing.Any) -> str:207    """Format arguments into a key=value line.208209    >>> formatkv(x=1, name="Bob")210    "x=1 name='Bob'"211    """212    return " ".join(f"{key}={value!r}" for key, value in kwargs.items())213214215def get_environment_proxies() -> typing.Dict[str, str]:216    """Gets proxy information from the environment"""217218    # urllib.request.getproxies() falls back on System219    # Registry and Config for proxies on Windows and macOS.220    # We don't want to propagate non-HTTP proxies into221    # our configuration such as 'TRAVIS_APT_PROXY'.222    proxies = {223        key: val224        for key, val in getproxies().items()225        if ("://" in key or key in ("http", "https"))226    }227228    # Favor lowercase environment variables over uppercase.229    all_proxy = get_environ_lower_and_upper("ALL_PROXY")230    if all_proxy is not None:231        proxies["all"] = all_proxy232233    return proxies234235236def get_environ_lower_and_upper(key: str) -> typing.Optional[str]:237    """Gets a value from os.environ with both the lowercase and uppercase238    environment variable. Prioritizes the lowercase environment variable.239    """240    for key in (key.lower(), key.upper()):241        value = os.environ.get(key, None)242        if value is not None and isinstance(value, str):243            return value244    return None245246247def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:248    return value.encode(encoding) if isinstance(value, str) else value249250251def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:252    return value if isinstance(value, str) else value.decode(encoding)253254255def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:256    return value if isinstance(match_type_of, str) else value.encode()257258259def unquote(value: str) -> str:260    return value[1:-1] if value[0] == value[-1] == '"' else value261262263def flatten_queryparams(264    queryparams: typing.Mapping[265        str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]266    ]267) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:268    """269    Convert a mapping of query params into a flat list of two-tuples270    representing each item.271272    Example:273    >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})274    [("q", "httpx), ("tag", "python"), ("tag", "dev")]275    """276    items = []277278    for k, v in queryparams.items():279        if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):280            for u in v:281                items.append((k, u))282        else:283            items.append((k, typing.cast("PrimitiveData", v)))284285    return items286287288class ElapsedTimer:289    def __init__(self) -> None:290        self.start: float = perf_counter()291        self.end: typing.Optional[float] = None292293    def __enter__(self) -> "ElapsedTimer":294        self.start = perf_counter()295        return self296297    def __exit__(298        self,299        exc_type: typing.Type[BaseException] = None,300        exc_value: BaseException = None,301        traceback: TracebackType = None,302    ) -> None:303        self.end = perf_counter()304305    @property306    def elapsed(self) -> timedelta:307        if self.end is None:308            return timedelta(seconds=perf_counter() - self.start)309        return timedelta(seconds=self.end - self.start)310311312ASGI_PLACEHOLDER_FORMAT = {313    "body": "<{length} bytes>",314    "bytes": "<{length} bytes>",315    "text": "<{length} chars>",316}317318319def asgi_message_with_placeholders(message: dict) -> dict:320    """321    Return an ASGI message, with any body-type content omitted and replaced322    with a placeholder.323    """324    new_message = message.copy()325326    for attr in ASGI_PLACEHOLDER_FORMAT:327        if attr in message:328            content = message[attr]329            placeholder = ASGI_PLACEHOLDER_FORMAT[attr].format(length=len(content))330            new_message[attr] = placeholder331332    if "headers" in message:333        new_message["headers"] = list(obfuscate_sensitive_headers(message["headers"]))334335    return new_message336337338class MessageLoggerASGIMiddleware:339    def __init__(self, app: typing.Callable, logger: logging.Logger) -> None:340        self.app = app341        self.logger = logger342343    async def __call__(344        self, scope: dict, receive: typing.Callable, send: typing.Callable345    ) -> None:346        async def inner_receive() -> dict:347            message = await receive()348            logged_message = asgi_message_with_placeholders(message)349            self.logger.debug(f"sent {kv_format(**logged_message)}")350            return message351352        async def inner_send(message: dict) -> None:353            logged_message = asgi_message_with_placeholders(message)354            self.logger.debug(f"received {kv_format(**logged_message)}")355            await send(message)356357        logged_scope = dict(scope)358        if "headers" in scope:359            logged_scope["headers"] = list(360                obfuscate_sensitive_headers(scope["headers"])361            )362        self.logger.debug(f"started {kv_format(**logged_scope)}")363364        try:365            await self.app(scope, inner_receive, inner_send)366        except BaseException as exc:367            self.logger.debug("raised_exception")368            raise exc from None369        else:370            self.logger.debug("completed")