Skip to content
Myr

Refactor netrc handling (#558)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Refactor netrc handling * Linting * Import sorting * Import sorting

authored by Tom Christie · committed by GitHub · parent 99ee84e · Browse files · 3 files+37 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+37 added−44 removed

  • tests:+6 added−17 removed
  • other:+31 added−27 removed

3 files+37 added−44 removed

modified:httpx/client.py+6 added-13 removed
1import functools2import netrc2import typing3from types import TracebackType45import hstspreload
39 unmodified lines
45 Response,46 URLTypes,47)48from .status_codes import codes50from .utils import ElapsedTimer, get_environment_proxies, get_logger, get_netrc49from .utils import ElapsedTimer, NetRCInfo, get_environment_proxies, get_logger5051logger = get_logger(__name__)5253
102 unmodified lines
156 self.max_redirects = max_redirects157 self.trust_env = trust_env158 self.dispatch = dispatch159 self.concurrency_backend = backend160 self.netrc = NetRCInfo()161162 if proxies is None and trust_env:163 proxies = typing.cast(ProxiesTypes, get_environment_proxies())164
219 unmodified lines
384 auth = BasicAuth(username=username, password=password)385 return auth(request)386387 if trust_env:388 netrc_info = self._get_netrc()389 if netrc_info is not None:390 netrc_login = netrc_info.authenticators(request.url.authority)391 netrc_username, _, netrc_password = netrc_login or ("", None, None)392 if netrc_password is not None:393 auth = BasicAuth(username=netrc_username, password=netrc_password)394 return auth(request)388 credentials = self.netrc.get_credentials(request.url.authority)389 if credentials is not None:390 auth = BasicAuth(username=credentials[0], password=credentials[1])391 return auth(request)392393 return request394395 async def send_handling_redirects(
163 unmodified lines
559 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')560561 return response562566 @functools.lru_cache(1)567 def _get_netrc(self) -> typing.Optional[netrc.netrc]:568 return get_netrc()569563 def _dispatcher_for_request(564 self, request: Request, proxies: typing.Dict[str, Dispatcher]565 ) -> Dispatcher:566 """Gets the Dispatcher instance that should be used for a given Request"""
304 unmodified lines
modified:httpx/utils.py+25 added-14 removed
94 unmodified lines
95 # Did not detect a valid UTF-32 ascii-range character96 return None979899NETRC_STATIC_FILES = (Path("~/.netrc"), Path("~/_netrc"))99class 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_info115102def get_netrc() -> typing.Optional[netrc.netrc]:103 NETRC_FILES = (Path(os.getenv("NETRC", "")),) + NETRC_STATIC_FILES104 netrc_path = None116 def get_credentials(117 self, authority: str118 ) -> typing.Optional[typing.Tuple[str, str]]:119 if self.netrc_info is None:120 return None121106 for file_path in NETRC_FILES:107 expanded_path = file_path.expanduser()108 if expanded_path.is_file():109 netrc_path = expanded_path110 break122 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])126112 if netrc_path is None:113 return None114 return netrc.netrc(str(netrc_path))127116128def 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():
60 unmodified lines
192193class Logger(logging.Logger):194 # Stub for type checkers.195 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:185 ...196 ... # pragma: nocover197198199def get_logger(name: str) -> Logger:200 """
202 unmodified lines
modified:tests/test_utils.py+6 added-17 removed
4 unmodified lines
56import httpx7from httpx.utils import (8 ElapsedTimer,9 NetRCInfo,10 get_ca_bundle_from_env,11 get_environment_proxies,11 get_netrc,12 guess_json_utf,13 obfuscate_sensitive_headers,14 parse_header_links,15 should_not_be_proxied,
37 unmodified lines
53 assert guess_json_utf(data) == expected545556def test_bad_get_netrc_login():57 os.environ["NETRC"] = "tests/.netrc"58 assert str(get_netrc()) is not None57 netrc_info = NetRCInfo(["tests/does-not-exist"])58 assert netrc_info.get_credentials("netrcexample.org") is None5960 from httpx import utils6062 utils.NETRC_STATIC_FILES = ()6364 os.environ["NETRC"] = "wrongpath"65 assert utils.get_netrc() is None6667 os.environ["NETRC"] = ""68 assert utils.get_netrc() is None697061def test_get_netrc_login():72 os.environ["NETRC"] = "tests/.netrc"73 netrc = get_netrc()74 assert netrc.authenticators("netrcexample.org") == (62 netrc_info = NetRCInfo(["tests/.netrc"])63 expected_credentials = (64 "example-username",76 None,65 "example-password",66 )67 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials686970@pytest.mark.parametrize(71 "value, expected",
216 unmodified lines