netrc parsing

This commit is contained in:
Kenneth Reitz
2012-02-20 15:35:19 -05:00
parent 2f33679cb3
commit 79bb9ee141
+33 -1
View File
@@ -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."""