Returns the Requests tuple auth for a given url from netrc.
(
url: _t.UriType, raise_errors: bool = False
)
| 229 | |
| 230 | |
| 231 | def get_netrc_auth( |
| 232 | url: _t.UriType, raise_errors: bool = False |
| 233 | ) -> tuple[str, str] | None: |
| 234 | """Returns the Requests tuple auth for a given url from netrc.""" |
| 235 | |
| 236 | if isinstance(url, bytes): |
| 237 | url = url.decode("utf-8") |
| 238 | |
| 239 | netrc_file = os.environ.get("NETRC") |
| 240 | if netrc_file is not None: |
| 241 | netrc_locations = (netrc_file,) |
| 242 | else: |
| 243 | netrc_locations = (f"~/{f}" for f in NETRC_FILES) |
| 244 | |
| 245 | try: |
| 246 | from netrc import NetrcParseError, netrc |
| 247 | |
| 248 | netrc_path = None |
| 249 | |
| 250 | for f in netrc_locations: |
| 251 | loc = os.path.expanduser(f) |
| 252 | if os.path.exists(loc): |
| 253 | netrc_path = loc |
| 254 | break |
| 255 | |
| 256 | # Abort early if there isn't one. |
| 257 | if netrc_path is None: |
| 258 | return |
| 259 | |
| 260 | ri = urlparse(url) |
| 261 | host = ri.hostname |
| 262 | |
| 263 | if host is None: |
| 264 | return |
| 265 | |
| 266 | try: |
| 267 | _netrc = netrc(netrc_path).authenticators(host) |
| 268 | if _netrc and any(_netrc): |
| 269 | # Return with login / password |
| 270 | login_i = 0 if _netrc[0] else 1 |
| 271 | return (_netrc[login_i] or "", _netrc[2] or "") |
| 272 | except (NetrcParseError, OSError): |
| 273 | # If there was a parsing error or a permissions issue reading the file, |
| 274 | # we'll just skip netrc auth unless explicitly asked to raise errors. |
| 275 | if raise_errors: |
| 276 | raise |
| 277 | |
| 278 | # App Engine hackiness. |
| 279 | except (ImportError, AttributeError): |
| 280 | pass |
| 281 | |
| 282 | |
| 283 | def guess_filename(obj: Any) -> str | None: |