From ba543713d35067866d68b09f644042c0c021a8ba Mon Sep 17 00:00:00 2001 From: Mathieu Pichette Date: Mon, 19 Oct 2020 09:36:52 -0700 Subject: Respect the NETRC environment variable --- docs/user/quickstart.rst | 3 ++- requests/utils.py | 10 ++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/user/quickstart.rst b/docs/user/quickstart.rst index c4fb9dd6..7b0450c4 100644 --- a/docs/user/quickstart.rst +++ b/docs/user/quickstart.rst @@ -213,7 +213,8 @@ Note: Custom headers are given less precedence than more specific sources of inf * Authorization headers set with `headers=` will be overridden if credentials are specified in ``.netrc``, which in turn will be overridden by the ``auth=`` - parameter. + parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`, + or at the path specified by the `NETRC` environment variable. * Authorization headers will be removed if you get redirected off-host. * Proxy-Authorization headers will be overridden by proxy credentials provided in the URL. * Content-Length headers will be overridden when we can determine the length of the content. diff --git a/requests/utils.py b/requests/utils.py index 1aafd9cb..16d57762 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -169,14 +169,20 @@ def super_len(o): def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" + netrc_file = os.environ.get('NETRC') + if netrc_file is not None: + netrc_locations = (netrc_file,) + else: + netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES) + try: from netrc import netrc, NetrcParseError netrc_path = None - for f in NETRC_FILES: + for f in netrc_locations: try: - loc = os.path.expanduser('~/{}'.format(f)) + loc = os.path.expanduser(f) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & -- cgit v1.2.1