From 79bb9ee1417afe2231972c1331308500104e5dc7 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Mon, 20 Feb 2012 15:35:19 -0500 Subject: [PATCH] netrc parsing --- requests/utils.py | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/requests/utils.py b/requests/utils.py index 97f5860..c9f5ad7 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -11,15 +11,47 @@ that are also useful for external consumption. import cgi import codecs +import os import random import re import zlib +from netrc import netrc, NetrcParseError from .compat import parse_http_list as _parse_list_header -from .compat import quote, cookielib, SimpleCookie, is_py2 +from .compat import quote, cookielib, SimpleCookie, is_py2, urlparse from .compat import basestring, bytes +NETRC_FILES = ('.netrc', '_netrc') + + +def get_netrc_auth(url): + """Returns the Requests tuple auth for a given url from netrc.""" + + locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) + netrc_path = None + + for loc in locations: + if os.path.exists(loc) and not netrc_path: + netrc_path = loc + + # Abort early if there isn't one. + if netrc_path is None: + return netrc_path + + ri = urlparse(url) + + # Strip port numbers from netloc + host = ri.netloc.split(':')[0] + + try: + _netrc = netrc(netrc_path).authenticators(host) + # Return with login / password + return (_netrc[0 if _netrc[0] else 1], _netrc[2]) + except NetrcParseError: + pass + + def dict_from_string(s): """Returns a MultiDict with Cookies.""" -- 2.7.4