utils.py
This file
Path
httpx/utils.py
369 lines · 11.3 KiB · Python
Last changed by
Wrap network errors in HTTPX-specific exceptions (#707)Florimond Mancabefore adoptione1afbfa
History of this fileTake it
1import codecs2import collections3import contextlib4import logging5import netrc6import os7import re8import sys9import typing10from datetime import timedelta11from pathlib import Path12from time import perf_counter13from types import TracebackType14from urllib.request import getproxies1516from .exceptions import NetworkError1718if typing.TYPE_CHECKING: # pragma: no cover19 from .models import PrimitiveData20 from .models import URL212223_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}24_HTML5_FORM_ENCODING_REPLACEMENTS.update(25 {chr(c): "%{:02X}".format(c) for c in range(0x00, 0x1F + 1) if c != 0x1B}26)27_HTML5_FORM_ENCODING_RE = re.compile(28 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])29)303132def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:33 """34 Coerce str/bytes into a strictly byte-wise HTTP header key.35 """36 if isinstance(value, bytes):37 return value.lower()38 return value.encode(encoding or "ascii").lower()394041def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:42 """43 Coerce str/bytes into a strictly byte-wise HTTP header value.44 """45 if isinstance(value, bytes):46 return value47 return value.encode(encoding or "ascii")484950def str_query_param(value: "PrimitiveData") -> str:51 """52 Coerce a primitive data type into a string value for query params.5354 Note that we prefer JSON-style 'true'/'false' for boolean values here.55 """56 if value is True:57 return "true"58 elif value is False:59 return "false"60 elif value is None:61 return ""62 return str(value)636465def is_known_encoding(encoding: str) -> bool:66 """67 Return `True` if `encoding` is a known codec.68 """69 try:70 codecs.lookup(encoding)71 except LookupError:72 return False73 return True747576def format_form_param(name: str, value: typing.Union[str, bytes]) -> bytes:77 """78 Encode a name/value pair within a multipart form.79 """80 if isinstance(value, bytes):81 value = value.decode()8283 def replacer(match: typing.Match[str]) -> str:84 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]8586 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)87 return f'{name}="{value}"'.encode()888990# Null bytes; no need to recreate these on each call to guess_json_utf91_null = "\x00".encode("ascii") # encoding to ASCII for Python 392_null2 = _null * 293_null3 = _null * 3949596def guess_json_utf(data: bytes) -> typing.Optional[str]:97 # JSON always starts with two ASCII characters, so detection is as98 # easy as counting the nulls and from their location and count99 # determine the encoding. Also detect a BOM, if present.100 sample = data[:4]101 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):102 return "utf-32" # BOM included103 if sample[:3] == codecs.BOM_UTF8:104 return "utf-8-sig" # BOM included, MS style (discouraged)105 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):106 return "utf-16" # BOM included107 nullcount = sample.count(_null)108 if nullcount == 0:109 return "utf-8"110 if nullcount == 2:111 if sample[::2] == _null2: # 1st and 3rd are null112 return "utf-16-be"113 if sample[1::2] == _null2: # 2nd and 4th are null114 return "utf-16-le"115 # Did not detect 2 valid UTF-16 ascii-range characters116 if nullcount == 3:117 if sample[:3] == _null3:118 return "utf-32-be"119 if sample[1:] == _null3:120 return "utf-32-le"121 # Did not detect a valid UTF-32 ascii-range character122 return None123124125class NetRCInfo:126 def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:127 if files is None:128 files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]129 self.netrc_files = files130131 @property132 def netrc_info(self) -> typing.Optional[netrc.netrc]:133 if not hasattr(self, "_netrc_info"):134 self._netrc_info = None135 for file_path in self.netrc_files:136 expanded_path = Path(file_path).expanduser()137 if expanded_path.is_file():138 self._netrc_info = netrc.netrc(str(expanded_path))139 break140 return self._netrc_info141142 def get_credentials(143 self, authority: str144 ) -> typing.Optional[typing.Tuple[str, str]]:145 if self.netrc_info is None:146 return None147148 auth_info = self.netrc_info.authenticators(authority)149 if auth_info is None or auth_info[2] is None:150 return None151 return (auth_info[0], auth_info[2])152153154def get_ca_bundle_from_env() -> typing.Optional[str]:155 if "SSL_CERT_FILE" in os.environ:156 ssl_file = Path(os.environ["SSL_CERT_FILE"])157 if ssl_file.is_file():158 return str(ssl_file)159 if "SSL_CERT_DIR" in os.environ:160 ssl_path = Path(os.environ["SSL_CERT_DIR"])161 if ssl_path.is_dir():162 return str(ssl_path)163 return None164165166def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:167 """168 Returns a list of parsed link headers, for more info see:169 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link170 The generic syntax of those is:171 Link: < uri-reference >; param1=value1; param2="value2"172 So for instance:173 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'174 would return175 [176 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},177 {"url": "http://.../back.jpeg"},178 ]179 :param value: HTTP Link entity-header field180 :return: list of parsed link headers181 """182 links: typing.List[typing.Dict[str, str]] = []183 replace_chars = " '\""184 value = value.strip(replace_chars)185 if not value:186 return links187 for val in re.split(", *<", value):188 try:189 url, params = val.split(";", 1)190 except ValueError:191 url, params = val, ""192 link = {"url": url.strip("<> '\"")}193 for param in params.split(";"):194 try:195 key, value = param.split("=")196 except ValueError:197 break198 link[key.strip(replace_chars)] = value.strip(replace_chars)199 links.append(link)200 return links201202203SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}204205206def obfuscate_sensitive_headers(207 items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]208) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:209 for k, v in items:210 if to_str(k.lower()) in SENSITIVE_HEADERS:211 v = to_bytes_or_str("[secure]", match_type_of=v)212 yield k, v213214215_LOGGER_INITIALIZED = False216TRACE_LOG_LEVEL = 5217218219class Logger(logging.Logger):220 # Stub for type checkers.221 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:222 ... # pragma: nocover223224225def get_logger(name: str) -> Logger:226 """227 Get a `logging.Logger` instance, and optionally228 set up debug logging based on the HTTPX_LOG_LEVEL environment variable.229 """230 global _LOGGER_INITIALIZED231232 if not _LOGGER_INITIALIZED:233 _LOGGER_INITIALIZED = True234 logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")235236 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()237 if log_level in ("DEBUG", "TRACE"):238 logger = logging.getLogger("httpx")239 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)240 handler = logging.StreamHandler(sys.stderr)241 handler.setFormatter(242 logging.Formatter(243 fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",244 datefmt="%Y-%m-%d %H:%M:%S",245 )246 )247 logger.addHandler(handler)248249 logger = logging.getLogger(name)250251 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:252 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)253254 logger.trace = trace # type: ignore255256 return typing.cast(Logger, logger)257258259def should_not_be_proxied(url: "URL") -> bool:260 """ Return True if url should not be proxied,261 return False otherwise.262 """263 no_proxy = getproxies().get("no")264 if not no_proxy:265 return False266 no_proxy_list = [host.strip() for host in no_proxy.split(",")]267 for name in no_proxy_list:268 if name == "*":269 return True270 if name:271 name = name.lstrip(".") # ignore leading dots272 name = re.escape(name)273 pattern = r"(.+\.)?%s$" % name274 if re.match(pattern, url.host, re.I) or re.match(275 pattern, url.authority, re.I276 ):277 return True278 return False279280281def get_environment_proxies() -> typing.Dict[str, str]:282 """Gets proxy information from the environment"""283284 # urllib.request.getproxies() falls back on System285 # Registry and Config for proxies on Windows and macOS.286 # We don't want to propagate non-HTTP proxies into287 # our configuration such as 'TRAVIS_APT_PROXY'.288 supported_proxy_schemes = ("http", "https", "all")289 return {290 key: val291 for key, val in getproxies().items()292 if ("://" in key or key in supported_proxy_schemes)293 }294295296def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:297 return value.encode(encoding) if isinstance(value, str) else value298299300def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:301 return value if isinstance(value, str) else value.decode(encoding)302303304def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:305 return value if isinstance(match_type_of, str) else value.encode()306307308def unquote(value: str) -> str:309 return value[1:-1] if value[0] == value[-1] == '"' else value310311312def flatten_queryparams(313 queryparams: typing.Mapping[314 str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]315 ]316) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:317 """318 Convert a mapping of query params into a flat list of two-tuples319 representing each item.320321 Example:322 >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})323 [("q", "httpx), ("tag", "python"), ("tag", "dev")]324 """325 items = []326327 for k, v in queryparams.items():328 if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):329 for u in v:330 items.append((k, u))331 else:332 items.append((k, typing.cast("PrimitiveData", v)))333334 return items335336337class ElapsedTimer:338 def __init__(self) -> None:339 self.start: float = perf_counter()340 self.end: typing.Optional[float] = None341342 def __enter__(self) -> "ElapsedTimer":343 self.start = perf_counter()344 return self345346 def __exit__(347 self,348 exc_type: typing.Type[BaseException] = None,349 exc_value: BaseException = None,350 traceback: TracebackType = None,351 ) -> None:352 self.end = perf_counter()353354 @property355 def elapsed(self) -> timedelta:356 if self.end is None:357 return timedelta(seconds=perf_counter() - self.start)358 return timedelta(seconds=self.end - self.start)359360361@contextlib.contextmanager362def as_network_error(*exception_classes: type) -> typing.Iterator[None]:363 try:364 yield365 except BaseException as exc:366 for cls in exception_classes:367 if isinstance(exc, cls):368 raise NetworkError(exc) from exc369 raise