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
Provenance
- Commit
abe0799- Tree
642806e- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
99ee84e
3 files changed+37 added−44 removed
modified:httpx/client.py+6 added-13 removed
1 import functools2-import netrc2 import typing3 from types import TracebackType4 5 import hstspreload39 unmodified lines45 Response,46 URLTypes,47 )48 from .status_codes import codes50-from .utils import ElapsedTimer, get_environment_proxies, get_logger, get_netrc49+from .utils import ElapsedTimer, NetRCInfo, get_environment_proxies, get_logger50 51 logger = get_logger(__name__)52 53 102 unmodified lines156 self.max_redirects = max_redirects157 self.trust_env = trust_env158 self.dispatch = dispatch159 self.concurrency_backend = backend160+ self.netrc = NetRCInfo()161 162 if proxies is None and trust_env:163 proxies = typing.cast(ProxiesTypes, get_environment_proxies())164 219 unmodified lines384 auth = BasicAuth(username=username, password=password)385 return auth(request)386 387 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)392 393 return request394 395 async def send_handling_redirects(163 unmodified lines559 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')560 561 return response562 566- @functools.lru_cache(1)567- def _get_netrc(self) -> typing.Optional[netrc.netrc]:568- return get_netrc()569-563 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 linesmodified:httpx/utils.py+25 added-14 removed
94 unmodified lines95 # Did not detect a valid UTF-32 ascii-range character96 return None97 98 99-NETRC_STATIC_FILES = (Path("~/.netrc"), Path("~/_netrc"))99+class 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 = files104 105+ @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_info115 102-def 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 None121 106- 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])126 112- if netrc_path is None:113- return None114- return netrc.netrc(str(netrc_path))127 116-128 def 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 lines192 193 class Logger(logging.Logger):194 # Stub for type checkers.195 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:185- ...196+ ... # pragma: nocover197 198 199 def get_logger(name: str) -> Logger:200 """202 unmodified linesmodified:tests/test_utils.py+6 added-17 removed
4 unmodified lines5 6 import httpx7 from 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 lines53 assert guess_json_utf(data) == expected54 55 56 def 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 None59 60- from httpx import utils60 62- utils.NETRC_STATIC_FILES = ()63-64- os.environ["NETRC"] = "wrongpath"65- assert utils.get_netrc() is None66-67- os.environ["NETRC"] = ""68- assert utils.get_netrc() is None69-70-61 def 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_credentials68 69 70 @pytest.mark.parametrize(71 "value, expected",216 unmodified lines