Cache netrc authentication per-client (#400)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Can Sarıgöl · committed by Seth Michael Larson · parent 5e4f54d · Browse files · 4 files·+29 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+29 added−18 removed
- tests:+9 added−9 removed
- other:+20 added−9 removed
Provenance
- Commit
84731c8- Tree
9eadcb7- Author
Can Sarıgöl <cansarigol@derinbilgi.com.tr>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
5e4f54d
4 files changed+29 added−18 removed
modified:docs/advanced.md+5 added
89 unmodified lines9091929394959697989910010110267 unmodified lines89 unmodified lines
HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter isnot defined, HTTPX tries to add auth into request's header from .netrc file.
!!! note The NETRC file is cached across requests made by a client. If you need to refresh the cache (e.g. because the NETRC file has changed), you should create a new client or restart the interpreter.
As default `trust_env` is true. To set false:```python>>> httpx.get('https://example.org/', trust_env=False)```67 unmodified linesmodified:httpx/client.py+13 added-5 removed
1 import functools2 import inspect3+import netrc4 import typing5 from types import TracebackType6 7 import hstspreload40 unmodified lines48 Response,49 ResponseContent,50 URLTypes,51 )51-from .utils import ElapsedTimer, get_environment_proxies, get_netrc_login52+from .utils import ElapsedTimer, get_environment_proxies, get_netrc53 54 55 class BaseClient:56 def __init__(220 unmodified lines277 username=request.url.username, password=request.url.password278 )279 280 if trust_env:280- netrc_login = get_netrc_login(request.url.authority)281- if netrc_login:282- username, _, password = netrc_login283- return BasicAuthMiddleware(username=username, password=password)281+ netrc_info = self._get_netrc()282+ if netrc_info:283+ netrc_login = netrc_info.authenticators(request.url.authority)284+ if netrc_login:285+ username, _, password = netrc_login286+ assert password is not None287+ return BasicAuthMiddleware(username=username, password=password)288 289 return None290 291+ @functools.lru_cache(1)292+ def _get_netrc(self) -> typing.Optional[netrc.netrc]:293+ return get_netrc()294+295 def _dispatcher_for_request(296 self, request: AsyncRequest, proxies: typing.Dict[str, AsyncDispatcher]297 ) -> AsyncDispatcher:298 """Gets the AsyncDispatcher instance that should be used for a given Request"""778 unmodified linesmodified:httpx/utils.py+2 added-4 removed
96 unmodified lines97 98 NETRC_STATIC_FILES = (Path("~/.netrc"), Path("~/_netrc"))99 100 101-def get_netrc_login(host: str) -> typing.Optional[typing.Tuple[str, str, str]]:101+def get_netrc() -> typing.Optional[netrc.netrc]:102 NETRC_FILES = (Path(os.getenv("NETRC", "")),) + NETRC_STATIC_FILES103 netrc_path = None104 105 for file_path in NETRC_FILES:3 unmodified lines109 break110 111 if netrc_path is None:112 return None113+ return netrc.netrc(str(netrc_path))114 114- netrc_info = netrc.netrc(str(netrc_path))115- return netrc_info.authenticators(host) # type: ignore115 117-116 def get_ca_bundle_from_env() -> typing.Optional[str]:117 if "SSL_CERT_FILE" in os.environ:118 ssl_file = Path(os.environ["SSL_CERT_FILE"])119 if ssl_file.is_file():232 unmodified linesmodified:tests/test_utils.py+9 added-9 removed
8 unmodified lines9 from httpx.utils import (10 ElapsedTimer,11 get_ca_bundle_from_env,12 get_environment_proxies,13- get_netrc_login,13+ get_netrc,14 guess_json_utf,15 obfuscate_sensitive_headers,16 parse_header_links,17 )35 unmodified lines53 assert guess_json_utf(data) == expected54 55 56 def test_bad_get_netrc_login():57- assert get_netrc_login("url") is None58-57 os.environ["NETRC"] = "tests/.netrc"60- assert get_netrc_login("url") is None58+ assert str(get_netrc()) is not None59 62- os.environ["NETRC"] = "wrongpath"63- assert get_netrc_login("url") is None64-60 from httpx import utils61 62 utils.NETRC_STATIC_FILES = ()63+64+ os.environ["NETRC"] = "wrongpath"65+ assert utils.get_netrc() is None66+67 os.environ["NETRC"] = ""69- assert utils.get_netrc_login("url") is None68+ assert utils.get_netrc() is None69 70 71 def test_get_netrc_login():72 os.environ["NETRC"] = "tests/.netrc"73+ netrc = get_netrc()74- assert get_netrc_login("netrcexample.org") == (74+ assert netrc.authenticators("netrcexample.org") == (75 "example-username",76 None,77 "example-password",78 )125 unmodified lines