# We only want to normalize urls with an HTTP(S) scheme. # urllib3 infers URLs without a scheme (None) to be http.
# Almost all of these patterns were derived from the # 'rfc3986' module: https://github.com/python-hyper/rfc3986 r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" r"(?://([^\\/?#]*))?" r"([^?#]*)" r"(?:\?([^#]*))?" r"(?:#(.*))?$", re.UNICODE | re.DOTALL, )
# 6( h16 ":" ) ls32 "(?:%(hex)s:){6}%(ls32)s", # "::" 5( h16 ":" ) ls32 "::(?:%(hex)s:){5}%(ls32)s", # [ h16 ] "::" 4( h16 ":" ) ls32 "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", # [ *4( h16 ":" ) h16 ] "::" ls32 "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", # [ *5( h16 ":" ) h16 ] "::" h16 "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", # [ *6( h16 ":" ) h16 ] "::" "(?:(?:%(hex)s:){0,6}%(hex)s)?::", ]
REG_NAME_PAT, IPV4_PAT, IPV6_ADDRZ_PAT, )
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" )
""" Data structure for representing an HTTP URL. Used as a return value for :func:`parse_url`. Both the scheme and host are normalized as they are both case-insensitive according to RFC 3986. """
cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None, ): path = "/" + path cls, scheme, auth, host, port, path, query, fragment )
def hostname(self): """For backwards-compatibility with urlparse. We're nice like that.""" return self.host
def request_uri(self): """Absolute path including the query string.""" uri = self.path or "/"
if self.query is not None: uri += "?" + self.query
return uri
def netloc(self): """Network location including host and port""" if self.port: return "%s:%d" % (self.host, self.port) return self.host
def url(self): """ Convert self into a url
This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed).
Example: ::
>>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = u""
# We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + u"://" if auth is not None: url += auth + u"@" if host is not None: url += host if port is not None: url += u":" + str(port) if path is not None: url += path if query is not None: url += u"?" + query if fragment is not None: url += u"#" + fragment
return url
def __str__(self): return self.url
""" .. deprecated:: 1.25
Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue
if min_idx is None or idx < min_idx: min_idx = idx min_delim = d
if min_idx is None or min_idx < 0: return s, "", None
return s[:min_idx], s[min_idx + 1 :], min_delim
"""Percent-encodes a URI component without reapplying onto an already percent-encoded component. """
# Normalize existing percent-encoded bytes. # Try to see if the component we're encoding is already percent-encoded # so we can skip all '%' characters but still encode all others. lambda match: match.group(0).upper(), component )
# Will return a single character bytestring on both Python 2 & 3 byte_ord < 128 and byte.decode() in allowed_chars ): encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))
# See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code
# '.' is the current directory, so ignore it, it is superfluous continue # Anything other than '..', should be appended to the output # In this case segment == '..', if we can, we should pop the last # element elif output: output.pop()
# If the path starts with '/' and the output is empty or the first string # is non-empty output.insert(0, "")
# If the path starts with '/.' or '/..' ensure we add one more empty # string to add a trailing '/' output.append("")
host = six.ensure_str(host)
match = ZONE_ID_RE.search(host) if match: start, end = match.span(1) zone_id = host[start:end]
if zone_id.startswith("%25") and zone_id != "%25": zone_id = zone_id[3:] else: zone_id = zone_id[1:] zone_id = "%" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS) return host[:start].lower() + zone_id + host[end:] else: return host.lower() b".".join([_idna_encode(label) for label in host.split(".")]) ) return host
try: import idna except ImportError: six.raise_from( LocationParseError("Unable to parse URL without the 'idna' module"), None, ) try: return idna.encode(name.lower(), strict=True, std3_rules=True) except idna.IDNAError: six.raise_from( LocationParseError(u"Name '%s' is not a valid IDNA label" % name), None )
"""Percent-encodes a request target so that there are no invalid characters""" target += "?" + query
""" Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 compliant.
The parser logic and helper functions are based heavily on work done in the ``rfc3986`` module.
:param str url: URL to parse into a :class:`.Url` namedtuple.
Partly backwards-compatible with :mod:`urlparse`.
Example::
>>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/mail/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) """ # Empty return Url()
url = "//" + url
auth = _encode_invalid_chars(auth, USERINFO_CHARS) port = None else: auth, host, port = None, None, None
port = int(port) if not (0 <= port <= 65535): raise LocationParseError(url)
query = _encode_invalid_chars(query, QUERY_CHARS) fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)
except (ValueError, AttributeError): return six.raise_from(LocationParseError(source_url), None)
# For the sake of backwards compatibility we put empty # string values for path if there are any defined values # beyond the path in the URL. # TODO: Remove this when we break backwards compatibility. if query is not None or fragment is not None: path = "" else: path = None
# Ensure that each part of the URL is a `str` for # backwards compatibility. else: ensure_func = six.ensure_str
scheme=ensure_type(scheme), auth=ensure_type(auth), host=ensure_type(host), port=port, path=ensure_type(path), query=ensure_type(query), fragment=ensure_type(fragment), )
""" Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or "http", p.hostname, p.port |