blob: f21b8eb49cca2293ad71b2b4a7cf5135dcf5e19a [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""Parse (absolute and relative) URLs.
2
Senthil Kumaranfd41e082010-04-17 14:44:14 +00003urlparse module is based upon the following RFC specifications.
4
5RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
6and L. Masinter, January 2005.
7
8RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
9and L.Masinter, December 1999.
10
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000011RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T.
Senthil Kumaranfd41e082010-04-17 14:44:14 +000012Berners-Lee, R. Fielding, and L. Masinter, August 1998.
13
David Malcolmee255682010-12-02 16:41:00 +000014RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.
Senthil Kumaranfd41e082010-04-17 14:44:14 +000015
16RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
171995.
18
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000019RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
Senthil Kumaranfd41e082010-04-17 14:44:14 +000020McCahill, December 1994
21
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000022RFC 3986 is considered the current standard and any future changes to
23urlparse module should conform with it. The urlparse module is
24currently not entirely compliant with this RFC due to defacto
25scenarios for parsing, and for backward compatibility purposes, some
26parsing quirks from older RFCs are retained. The testcases in
Senthil Kumaranfd41e082010-04-17 14:44:14 +000027test_urlparse.py provides a good indicator of parsing behavior.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000028"""
29
Serhiy Storchaka8ea46162013-03-14 21:31:37 +020030import re
Facundo Batista2ac5de22008-07-07 18:24:11 +000031import sys
Guido van Rossum52dbbb92008-08-18 21:44:30 +000032import collections
Cheryl Sabella0250de42018-04-25 16:51:54 -070033import warnings
Facundo Batista2ac5de22008-07-07 18:24:11 +000034
Jeremy Hylton1afc1692008-06-18 20:49:58 +000035__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
Senthil Kumaran0256b2a2010-10-25 16:36:20 +000036 "urlsplit", "urlunsplit", "urlencode", "parse_qs",
37 "parse_qsl", "quote", "quote_plus", "quote_from_bytes",
Serhiy Storchaka15154502015-04-07 19:09:01 +030038 "unquote", "unquote_plus", "unquote_to_bytes",
39 "DefragResult", "ParseResult", "SplitResult",
40 "DefragResultBytes", "ParseResultBytes", "SplitResultBytes"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +000041
Senthil Kumaran906f5332017-05-17 21:48:59 -070042# A classification of schemes.
43# The empty string classifies URLs with no scheme specified,
44# being the default value returned by “urlsplit” and “urlparse”.
45
46uses_relative = ['', 'ftp', 'http', 'gopher', 'nntp', 'imap',
Jeremy Hylton1afc1692008-06-18 20:49:58 +000047 'wais', 'file', 'https', 'shttp', 'mms',
Senthil Kumaran906f5332017-05-17 21:48:59 -070048 'prospero', 'rtsp', 'rtspu', 'sftp',
Berker Peksagf6767482016-09-16 14:43:58 +030049 'svn', 'svn+ssh', 'ws', 'wss']
Senthil Kumaran906f5332017-05-17 21:48:59 -070050
51uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet',
Jeremy Hylton1afc1692008-06-18 20:49:58 +000052 'imap', 'wais', 'file', 'mms', 'https', 'shttp',
Senthil Kumaran906f5332017-05-17 21:48:59 -070053 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync',
Berker Peksagf6767482016-09-16 14:43:58 +030054 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
55 'ws', 'wss']
Senthil Kumaran906f5332017-05-17 21:48:59 -070056
57uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
Jeremy Hylton1afc1692008-06-18 20:49:58 +000058 'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
Senthil Kumaran906f5332017-05-17 21:48:59 -070059 'mms', 'sftp', 'tel']
Jeremy Hylton1afc1692008-06-18 20:49:58 +000060
Georg Brandla61b09f2012-08-24 18:15:29 +020061# These are not actually used anymore, but should stay for backwards
62# compatibility. (They are undocumented, but have a public-looking name.)
Senthil Kumaran906f5332017-05-17 21:48:59 -070063
Georg Brandla61b09f2012-08-24 18:15:29 +020064non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
65 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
Senthil Kumaran906f5332017-05-17 21:48:59 -070066
67uses_query = ['', 'http', 'wais', 'imap', 'https', 'shttp', 'mms',
68 'gopher', 'rtsp', 'rtspu', 'sip', 'sips']
69
70uses_fragment = ['', 'ftp', 'hdl', 'http', 'gopher', 'news',
Georg Brandla61b09f2012-08-24 18:15:29 +020071 'nntp', 'wais', 'https', 'shttp', 'snews',
Senthil Kumaran906f5332017-05-17 21:48:59 -070072 'file', 'prospero']
Georg Brandla61b09f2012-08-24 18:15:29 +020073
Jeremy Hylton1afc1692008-06-18 20:49:58 +000074# Characters valid in scheme names
75scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
76 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
77 '0123456789'
78 '+-.')
79
Nick Coghlan9fc443c2010-11-30 15:48:08 +000080# XXX: Consider replacing with functools.lru_cache
Jeremy Hylton1afc1692008-06-18 20:49:58 +000081MAX_CACHE_SIZE = 20
82_parse_cache = {}
83
84def clear_cache():
Antoine Pitrou2df5fc72009-12-08 19:38:17 +000085 """Clear the parse cache and the quoters cache."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +000086 _parse_cache.clear()
Antoine Pitrou2df5fc72009-12-08 19:38:17 +000087 _safe_quoters.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000088
89
Nick Coghlan9fc443c2010-11-30 15:48:08 +000090# Helpers for bytes handling
91# For 3.2, we deliberately require applications that
92# handle improperly quoted URLs to do their own
93# decoding and encoding. If valid use cases are
94# presented, we may relax this by using latin-1
95# decoding internally for 3.3
96_implicit_encoding = 'ascii'
97_implicit_errors = 'strict'
98
99def _noop(obj):
100 return obj
101
102def _encode_result(obj, encoding=_implicit_encoding,
103 errors=_implicit_errors):
104 return obj.encode(encoding, errors)
105
106def _decode_args(args, encoding=_implicit_encoding,
107 errors=_implicit_errors):
108 return tuple(x.decode(encoding, errors) if x else '' for x in args)
109
110def _coerce_args(*args):
111 # Invokes decode if necessary to create str args
112 # and returns the coerced inputs along with
113 # an appropriate result coercion function
114 # - noop for str inputs
115 # - encoding function otherwise
116 str_input = isinstance(args[0], str)
117 for arg in args[1:]:
118 # We special-case the empty string to support the
119 # "scheme=''" default argument to some functions
120 if arg and isinstance(arg, str) != str_input:
121 raise TypeError("Cannot mix str and non-str arguments")
122 if str_input:
123 return args + (_noop,)
124 return _decode_args(args) + (_encode_result,)
125
126# Result objects are more helpful than simple tuples
127class _ResultMixinStr(object):
128 """Standard approach to encoding parsed results from str to bytes"""
129 __slots__ = ()
130
131 def encode(self, encoding='ascii', errors='strict'):
132 return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
133
134
135class _ResultMixinBytes(object):
136 """Standard approach to decoding parsed results from bytes to str"""
137 __slots__ = ()
138
139 def decode(self, encoding='ascii', errors='strict'):
140 return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
141
142
143class _NetlocResultMixinBase(object):
144 """Shared methods for the parsed result objects containing a netloc element"""
145 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000146
147 @property
148 def username(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000149 return self._userinfo[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000150
151 @property
152 def password(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000153 return self._userinfo[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000154
155 @property
156 def hostname(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000157 hostname = self._hostinfo[0]
158 if not hostname:
Коренберг Маркfbd60512017-12-21 17:16:17 +0500159 return None
160 # Scoped IPv6 address may have zone info, which must not be lowercased
161 # like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys
162 separator = '%' if isinstance(hostname, str) else b'%'
163 hostname, percent, zone = hostname.partition(separator)
164 return hostname.lower() + percent + zone
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000165
166 @property
167 def port(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000168 port = self._hostinfo[1]
169 if port is not None:
Matt Eaton2cb46612018-03-20 01:41:37 -0500170 try:
171 port = int(port, 10)
172 except ValueError:
173 message = f'Port could not be cast to integer value as {port!r}'
174 raise ValueError(message) from None
Senthil Kumaran2fc5a502012-05-24 21:56:17 +0800175 if not ( 0 <= port <= 65535):
Robert Collinsdfa95c92015-08-10 09:53:30 +1200176 raise ValueError("Port out of range 0-65535")
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000177 return port
178
179
180class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
181 __slots__ = ()
182
183 @property
184 def _userinfo(self):
185 netloc = self.netloc
186 userinfo, have_info, hostinfo = netloc.rpartition('@')
187 if have_info:
188 username, have_password, password = userinfo.partition(':')
189 if not have_password:
190 password = None
Senthil Kumaranad02d232010-04-16 03:02:13 +0000191 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000192 username = password = None
193 return username, password
194
195 @property
196 def _hostinfo(self):
197 netloc = self.netloc
198 _, _, hostinfo = netloc.rpartition('@')
199 _, have_open_br, bracketed = hostinfo.partition('[')
200 if have_open_br:
201 hostname, _, port = bracketed.partition(']')
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200202 _, _, port = port.partition(':')
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000203 else:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200204 hostname, _, port = hostinfo.partition(':')
205 if not port:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000206 port = None
207 return hostname, port
208
209
210class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
211 __slots__ = ()
212
213 @property
214 def _userinfo(self):
215 netloc = self.netloc
216 userinfo, have_info, hostinfo = netloc.rpartition(b'@')
217 if have_info:
218 username, have_password, password = userinfo.partition(b':')
219 if not have_password:
220 password = None
221 else:
222 username = password = None
223 return username, password
224
225 @property
226 def _hostinfo(self):
227 netloc = self.netloc
228 _, _, hostinfo = netloc.rpartition(b'@')
229 _, have_open_br, bracketed = hostinfo.partition(b'[')
230 if have_open_br:
231 hostname, _, port = bracketed.partition(b']')
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200232 _, _, port = port.partition(b':')
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000233 else:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200234 hostname, _, port = hostinfo.partition(b':')
235 if not port:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000236 port = None
237 return hostname, port
238
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000239
240from collections import namedtuple
241
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000242_DefragResultBase = namedtuple('DefragResult', 'url fragment')
Senthil Kumaran86f71092016-01-14 00:11:39 -0800243_SplitResultBase = namedtuple(
244 'SplitResult', 'scheme netloc path query fragment')
245_ParseResultBase = namedtuple(
246 'ParseResult', 'scheme netloc path params query fragment')
247
248_DefragResultBase.__doc__ = """
249DefragResult(url, fragment)
250
251A 2-tuple that contains the url without fragment identifier and the fragment
252identifier as a separate argument.
253"""
254
255_DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""
256
257_DefragResultBase.fragment.__doc__ = """
258Fragment identifier separated from URL, that allows indirect identification of a
259secondary resource by reference to a primary resource and additional identifying
260information.
261"""
262
263_SplitResultBase.__doc__ = """
264SplitResult(scheme, netloc, path, query, fragment)
265
266A 5-tuple that contains the different components of a URL. Similar to
267ParseResult, but does not split params.
268"""
269
270_SplitResultBase.scheme.__doc__ = """Specifies URL scheme for the request."""
271
272_SplitResultBase.netloc.__doc__ = """
273Network location where the request is made to.
274"""
275
276_SplitResultBase.path.__doc__ = """
277The hierarchical path, such as the path to a file to download.
278"""
279
280_SplitResultBase.query.__doc__ = """
281The query component, that contains non-hierarchical data, that along with data
282in path component, identifies a resource in the scope of URI's scheme and
283network location.
284"""
285
286_SplitResultBase.fragment.__doc__ = """
287Fragment identifier, that allows indirect identification of a secondary resource
288by reference to a primary resource and additional identifying information.
289"""
290
291_ParseResultBase.__doc__ = """
Cheryl Sabella0250de42018-04-25 16:51:54 -0700292ParseResult(scheme, netloc, path, params, query, fragment)
Senthil Kumaran86f71092016-01-14 00:11:39 -0800293
294A 6-tuple that contains components of a parsed URL.
295"""
296
297_ParseResultBase.scheme.__doc__ = _SplitResultBase.scheme.__doc__
298_ParseResultBase.netloc.__doc__ = _SplitResultBase.netloc.__doc__
299_ParseResultBase.path.__doc__ = _SplitResultBase.path.__doc__
300_ParseResultBase.params.__doc__ = """
301Parameters for last path element used to dereference the URI in order to provide
302access to perform some operation on the resource.
303"""
304
305_ParseResultBase.query.__doc__ = _SplitResultBase.query.__doc__
306_ParseResultBase.fragment.__doc__ = _SplitResultBase.fragment.__doc__
307
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000308
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000309# For backwards compatibility, alias _NetlocResultMixinStr
310# ResultBase is no longer part of the documented API, but it is
311# retained since deprecating it isn't worth the hassle
312ResultBase = _NetlocResultMixinStr
313
314# Structured result objects for string data
315class DefragResult(_DefragResultBase, _ResultMixinStr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000316 __slots__ = ()
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000317 def geturl(self):
318 if self.fragment:
319 return self.url + '#' + self.fragment
320 else:
321 return self.url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000322
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000323class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
324 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000325 def geturl(self):
326 return urlunsplit(self)
327
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000328class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000329 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000330 def geturl(self):
331 return urlunparse(self)
332
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000333# Structured result objects for bytes data
334class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
335 __slots__ = ()
336 def geturl(self):
337 if self.fragment:
338 return self.url + b'#' + self.fragment
339 else:
340 return self.url
341
342class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
343 __slots__ = ()
344 def geturl(self):
345 return urlunsplit(self)
346
347class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
348 __slots__ = ()
349 def geturl(self):
350 return urlunparse(self)
351
352# Set up the encode/decode result pairs
353def _fix_result_transcoding():
354 _result_pairs = (
355 (DefragResult, DefragResultBytes),
356 (SplitResult, SplitResultBytes),
357 (ParseResult, ParseResultBytes),
358 )
359 for _decoded, _encoded in _result_pairs:
360 _decoded._encoded_counterpart = _encoded
361 _encoded._decoded_counterpart = _decoded
362
363_fix_result_transcoding()
364del _fix_result_transcoding
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000365
366def urlparse(url, scheme='', allow_fragments=True):
367 """Parse a URL into 6 components:
368 <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
369 Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
370 Note that we don't break the components up in smaller bits
371 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000372 url, scheme, _coerce_result = _coerce_args(url, scheme)
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700373 splitresult = urlsplit(url, scheme, allow_fragments)
374 scheme, netloc, url, query, fragment = splitresult
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000375 if scheme in uses_params and ';' in url:
376 url, params = _splitparams(url)
377 else:
378 params = ''
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000379 result = ParseResult(scheme, netloc, url, params, query, fragment)
380 return _coerce_result(result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000381
382def _splitparams(url):
383 if '/' in url:
384 i = url.find(';', url.rfind('/'))
385 if i < 0:
386 return url, ''
387 else:
388 i = url.find(';')
389 return url[:i], url[i+1:]
390
391def _splitnetloc(url, start=0):
392 delim = len(url) # position of end of domain part of url, default is end
393 for c in '/?#': # look for delimiters; the order is NOT important
394 wdelim = url.find(c, start) # find first of this delim
395 if wdelim >= 0: # if found
396 delim = min(delim, wdelim) # use earliest delim position
397 return url[start:delim], url[delim:] # return (domain, rest)
398
399def urlsplit(url, scheme='', allow_fragments=True):
400 """Parse a URL into 5 components:
401 <scheme>://<netloc>/<path>?<query>#<fragment>
402 Return a 5-tuple: (scheme, netloc, path, query, fragment).
403 Note that we don't break the components up in smaller bits
404 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000405 url, scheme, _coerce_result = _coerce_args(url, scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000406 allow_fragments = bool(allow_fragments)
407 key = url, scheme, allow_fragments, type(url), type(scheme)
408 cached = _parse_cache.get(key, None)
409 if cached:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000410 return _coerce_result(cached)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000411 if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
412 clear_cache()
413 netloc = query = fragment = ''
414 i = url.find(':')
415 if i > 0:
416 if url[:i] == 'http': # optimize the common case
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000417 url = url[i+1:]
418 if url[:2] == '//':
419 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000420 if (('[' in netloc and ']' not in netloc) or
421 (']' in netloc and '[' not in netloc)):
422 raise ValueError("Invalid IPv6 URL")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000423 if allow_fragments and '#' in url:
424 url, fragment = url.split('#', 1)
425 if '?' in url:
426 url, query = url.split('?', 1)
Oren Milman8df44ee2017-09-03 07:51:39 +0300427 v = SplitResult('http', netloc, url, query, fragment)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000428 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000429 return _coerce_result(v)
Senthil Kumaran397eb442011-04-15 18:20:24 +0800430 for c in url[:i]:
431 if c not in scheme_chars:
432 break
433 else:
Ezio Melotti6709b7d2012-05-19 17:15:19 +0300434 # make sure "url" is not actually a port number (in which case
435 # "scheme" is really part of the path)
436 rest = url[i+1:]
437 if not rest or any(c not in '0123456789' for c in rest):
438 # not a port number
439 scheme, url = url[:i].lower(), rest
Senthil Kumaran397eb442011-04-15 18:20:24 +0800440
Senthil Kumaran6be85c52010-02-19 07:42:50 +0000441 if url[:2] == '//':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000442 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000443 if (('[' in netloc and ']' not in netloc) or
444 (']' in netloc and '[' not in netloc)):
445 raise ValueError("Invalid IPv6 URL")
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800446 if allow_fragments and '#' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000447 url, fragment = url.split('#', 1)
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800448 if '?' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000449 url, query = url.split('?', 1)
450 v = SplitResult(scheme, netloc, url, query, fragment)
451 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000452 return _coerce_result(v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000453
454def urlunparse(components):
455 """Put a parsed URL back together again. This may result in a
456 slightly different, but equivalent URL, if the URL that was parsed
457 originally had redundant delimiters, e.g. a ? with an empty query
458 (the draft states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000459 scheme, netloc, url, params, query, fragment, _coerce_result = (
460 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000461 if params:
462 url = "%s;%s" % (url, params)
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000463 return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000464
465def urlunsplit(components):
Senthil Kumaran8749a632010-06-28 14:08:00 +0000466 """Combine the elements of a tuple as returned by urlsplit() into a
467 complete URL as a string. The data argument can be any five-item iterable.
468 This may result in a slightly different, but equivalent URL, if the URL that
469 was parsed originally had unnecessary delimiters (for example, a ? with an
470 empty query; the RFC states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000471 scheme, netloc, url, query, fragment, _coerce_result = (
472 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000473 if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
474 if url and url[:1] != '/': url = '/' + url
475 url = '//' + (netloc or '') + url
476 if scheme:
477 url = scheme + ':' + url
478 if query:
479 url = url + '?' + query
480 if fragment:
481 url = url + '#' + fragment
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000482 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000483
484def urljoin(base, url, allow_fragments=True):
485 """Join a base URL and a possibly relative URL to form an absolute
486 interpretation of the latter."""
487 if not base:
488 return url
489 if not url:
490 return base
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400491
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000492 base, url, _coerce_result = _coerce_args(base, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000493 bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
494 urlparse(base, '', allow_fragments)
495 scheme, netloc, path, params, query, fragment = \
496 urlparse(url, bscheme, allow_fragments)
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400497
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000498 if scheme != bscheme or scheme not in uses_relative:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000499 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000500 if scheme in uses_netloc:
501 if netloc:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000502 return _coerce_result(urlunparse((scheme, netloc, path,
503 params, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000504 netloc = bnetloc
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400505
Senthil Kumarandca5b862010-12-17 04:48:45 +0000506 if not path and not params:
Facundo Batista23e38562008-08-14 16:55:14 +0000507 path = bpath
Senthil Kumarandca5b862010-12-17 04:48:45 +0000508 params = bparams
Facundo Batista23e38562008-08-14 16:55:14 +0000509 if not query:
510 query = bquery
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000511 return _coerce_result(urlunparse((scheme, netloc, path,
512 params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400513
514 base_parts = bpath.split('/')
515 if base_parts[-1] != '':
516 # the last item is not a directory, so will not be taken into account
517 # in resolving the relative path
518 del base_parts[-1]
519
520 # for rfc3986, ignore all base path should the first character be root.
521 if path[:1] == '/':
522 segments = path.split('/')
523 else:
524 segments = base_parts + path.split('/')
Senthil Kumarana66e3882014-09-22 15:49:16 +0800525 # filter out elements that would cause redundant slashes on re-joining
526 # the resolved_path
Berker Peksag20416f72015-04-16 02:31:14 +0300527 segments[1:-1] = filter(None, segments[1:-1])
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400528
529 resolved_path = []
530
531 for seg in segments:
532 if seg == '..':
533 try:
534 resolved_path.pop()
535 except IndexError:
536 # ignore any .. segments that would otherwise cause an IndexError
537 # when popped from resolved_path if resolving for rfc3986
538 pass
539 elif seg == '.':
540 continue
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000541 else:
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400542 resolved_path.append(seg)
543
544 if segments[-1] in ('.', '..'):
545 # do some post-processing here. if the last segment was a relative dir,
546 # then we need to append the trailing '/'
547 resolved_path.append('')
548
549 return _coerce_result(urlunparse((scheme, netloc, '/'.join(
Senthil Kumarana66e3882014-09-22 15:49:16 +0800550 resolved_path) or '/', params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400551
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000552
553def urldefrag(url):
554 """Removes any existing fragment from URL.
555
556 Returns a tuple of the defragmented URL and the fragment. If
557 the URL contained no fragments, the second element is the
558 empty string.
559 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000560 url, _coerce_result = _coerce_args(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000561 if '#' in url:
562 s, n, p, a, q, frag = urlparse(url)
563 defrag = urlunparse((s, n, p, a, q, ''))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000564 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000565 frag = ''
566 defrag = url
567 return _coerce_result(DefragResult(defrag, frag))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000568
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200569_hexdig = '0123456789ABCDEFabcdef'
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100570_hextobyte = None
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200571
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000572def unquote_to_bytes(string):
573 """unquote_to_bytes('abc%20def') -> b'abc def'."""
574 # Note: strings are encoded as UTF-8. This is only an issue if it contains
575 # unescaped non-ASCII characters, which URIs should not.
Florent Xicluna82a3f8a2010-08-14 18:30:35 +0000576 if not string:
577 # Is it a string-like object?
578 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000579 return b''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000580 if isinstance(string, str):
581 string = string.encode('utf-8')
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200582 bits = string.split(b'%')
583 if len(bits) == 1:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000584 return string
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200585 res = [bits[0]]
586 append = res.append
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100587 # Delay the initialization of the table to not waste memory
588 # if the function is never called
589 global _hextobyte
590 if _hextobyte is None:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +0200591 _hextobyte = {(a + b).encode(): bytes.fromhex(a + b)
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100592 for a in _hexdig for b in _hexdig}
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200593 for item in bits[1:]:
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000594 try:
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200595 append(_hextobyte[item[:2]])
596 append(item[2:])
597 except KeyError:
598 append(b'%')
599 append(item)
600 return b''.join(res)
601
602_asciire = re.compile('([\x00-\x7f]+)')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000603
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000604def unquote(string, encoding='utf-8', errors='replace'):
605 """Replace %xx escapes by their single-character equivalent. The optional
606 encoding and errors parameters specify how to decode percent-encoded
607 sequences into Unicode characters, as accepted by the bytes.decode()
608 method.
609 By default, percent-encoded sequences are decoded with UTF-8, and invalid
610 sequences are replaced by a placeholder character.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000611
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000612 unquote('abc%20def') -> 'abc def'.
613 """
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200614 if '%' not in string:
615 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000616 return string
617 if encoding is None:
618 encoding = 'utf-8'
619 if errors is None:
620 errors = 'replace'
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200621 bits = _asciire.split(string)
622 res = [bits[0]]
623 append = res.append
624 for i in range(1, len(bits), 2):
625 append(unquote_to_bytes(bits[i]).decode(encoding, errors))
626 append(bits[i + 1])
627 return ''.join(res)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000628
Senthil Kumaran257b9802017-04-04 21:19:43 -0700629
Victor Stinnerac71c542011-01-14 12:52:12 +0000630def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
631 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000632 """Parse a query given as a string argument.
633
634 Arguments:
635
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000636 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000637
638 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000639 percent-encoded queries should be treated as blank strings.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000640 A true value indicates that blanks should be retained as
641 blank strings. The default false value indicates that
642 blank values are to be ignored and treated as if they were
643 not included.
644
645 strict_parsing: flag indicating what to do with parsing errors.
646 If false (the default), errors are silently ignored.
647 If true, errors raise a ValueError exception.
Victor Stinnerac71c542011-01-14 12:52:12 +0000648
649 encoding and errors: specify how to decode percent-encoded sequences
650 into Unicode characters, as accepted by the bytes.decode() method.
Senthil Kumaran257b9802017-04-04 21:19:43 -0700651
652 Returns a dictionary.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000653 """
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700654 parsed_result = {}
Victor Stinnerac71c542011-01-14 12:52:12 +0000655 pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
656 encoding=encoding, errors=errors)
657 for name, value in pairs:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700658 if name in parsed_result:
659 parsed_result[name].append(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000660 else:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700661 parsed_result[name] = [value]
662 return parsed_result
Facundo Batistac469d4c2008-09-03 22:49:01 +0000663
Senthil Kumaran257b9802017-04-04 21:19:43 -0700664
Victor Stinnerac71c542011-01-14 12:52:12 +0000665def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
666 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000667 """Parse a query given as a string argument.
668
Senthil Kumaran257b9802017-04-04 21:19:43 -0700669 Arguments:
Facundo Batistac469d4c2008-09-03 22:49:01 +0000670
Senthil Kumaran257b9802017-04-04 21:19:43 -0700671 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000672
Senthil Kumaran257b9802017-04-04 21:19:43 -0700673 keep_blank_values: flag indicating whether blank values in
674 percent-encoded queries should be treated as blank strings.
675 A true value indicates that blanks should be retained as blank
676 strings. The default false value indicates that blank values
677 are to be ignored and treated as if they were not included.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000678
Senthil Kumaran257b9802017-04-04 21:19:43 -0700679 strict_parsing: flag indicating what to do with parsing errors. If
680 false (the default), errors are silently ignored. If true,
681 errors raise a ValueError exception.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000682
Senthil Kumaran257b9802017-04-04 21:19:43 -0700683 encoding and errors: specify how to decode percent-encoded sequences
684 into Unicode characters, as accepted by the bytes.decode() method.
Victor Stinnerac71c542011-01-14 12:52:12 +0000685
Senthil Kumaran257b9802017-04-04 21:19:43 -0700686 Returns a list, as G-d intended.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000687 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000688 qs, _coerce_result = _coerce_args(qs)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000689 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
690 r = []
691 for name_value in pairs:
692 if not name_value and not strict_parsing:
693 continue
694 nv = name_value.split('=', 1)
695 if len(nv) != 2:
696 if strict_parsing:
697 raise ValueError("bad query field: %r" % (name_value,))
698 # Handle case of a control-name with no equal sign
699 if keep_blank_values:
700 nv.append('')
701 else:
702 continue
703 if len(nv[1]) or keep_blank_values:
Victor Stinnerac71c542011-01-14 12:52:12 +0000704 name = nv[0].replace('+', ' ')
705 name = unquote(name, encoding=encoding, errors=errors)
706 name = _coerce_result(name)
707 value = nv[1].replace('+', ' ')
708 value = unquote(value, encoding=encoding, errors=errors)
709 value = _coerce_result(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000710 r.append((name, value))
Facundo Batistac469d4c2008-09-03 22:49:01 +0000711 return r
712
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000713def unquote_plus(string, encoding='utf-8', errors='replace'):
714 """Like unquote(), but also replace plus signs by spaces, as required for
715 unquoting HTML form values.
716
717 unquote_plus('%7e/abc+def') -> '~/abc def'
718 """
719 string = string.replace('+', ' ')
720 return unquote(string, encoding, errors)
721
722_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
723 b'abcdefghijklmnopqrstuvwxyz'
724 b'0123456789'
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530725 b'_.-~')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000726_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
727_safe_quoters = {}
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000728
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000729class Quoter(collections.defaultdict):
730 """A mapping from bytes (in range(0,256)) to strings.
731
732 String values are percent-encoded byte values, unless the key < 128, and
733 in the "safe" set (either the specified safe set, or default set).
734 """
735 # Keeps a cache internally, using defaultdict, for efficiency (lookups
736 # of cached keys don't call Python code at all).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000737 def __init__(self, safe):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000738 """safe: bytes object."""
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000739 self.safe = _ALWAYS_SAFE.union(safe)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000740
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000741 def __repr__(self):
742 # Without this, will just display as a defaultdict
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300743 return "<%s %r>" % (self.__class__.__name__, dict(self))
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000744
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000745 def __missing__(self, b):
746 # Handle a cache miss. Store quoted string in cache and return.
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000747 res = chr(b) if b in self.safe else '%{:02X}'.format(b)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000748 self[b] = res
749 return res
750
751def quote(string, safe='/', encoding=None, errors=None):
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000752 """quote('abc def') -> 'abc%20def'
753
754 Each part of a URL, e.g. the path info, the query, etc., has a
755 different set of reserved characters that must be quoted.
756
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530757 RFC 3986 Uniform Resource Identifiers (URI): Generic Syntax lists
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000758 the following reserved characters.
759
760 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530761 "$" | "," | "~"
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000762
763 Each of these characters is reserved in some component of a URL,
764 but not necessarily in all of them.
765
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530766 Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
767 Now, "~" is included in the set of reserved characters.
768
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000769 By default, the quote function is intended for quoting the path
770 section of a URL. Thus, it will not encode '/'. This character
771 is reserved, but in typical usage the quote function is being
772 called on a path where the existing slash characters are used as
773 reserved characters.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000774
R David Murray8c4e1122014-12-24 21:23:18 -0500775 string and safe may be either str or bytes objects. encoding and errors
776 must not be specified if string is a bytes object.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000777
778 The optional encoding and errors parameters specify how to deal with
779 non-ASCII characters, as accepted by the str.encode method.
780 By default, encoding='utf-8' (characters are encoded with UTF-8), and
781 errors='strict' (unsupported characters raise a UnicodeEncodeError).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000782 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000783 if isinstance(string, str):
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000784 if not string:
785 return string
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000786 if encoding is None:
787 encoding = 'utf-8'
788 if errors is None:
789 errors = 'strict'
790 string = string.encode(encoding, errors)
791 else:
792 if encoding is not None:
793 raise TypeError("quote() doesn't support 'encoding' for bytes")
794 if errors is not None:
795 raise TypeError("quote() doesn't support 'errors' for bytes")
796 return quote_from_bytes(string, safe)
797
798def quote_plus(string, safe='', encoding=None, errors=None):
799 """Like quote(), but also replace ' ' with '+', as required for quoting
800 HTML form values. Plus signs in the original string are escaped unless
801 they are included in safe. It also does not have safe default to '/'.
802 """
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000803 # Check if ' ' in string, where string may either be a str or bytes. If
804 # there are no spaces, the regular quote will produce the right answer.
805 if ((isinstance(string, str) and ' ' not in string) or
806 (isinstance(string, bytes) and b' ' not in string)):
807 return quote(string, safe, encoding, errors)
808 if isinstance(safe, str):
809 space = ' '
810 else:
811 space = b' '
Georg Brandlfaf41492009-05-26 18:31:11 +0000812 string = quote(string, safe + space, encoding, errors)
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000813 return string.replace(' ', '+')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000814
815def quote_from_bytes(bs, safe='/'):
816 """Like quote(), but accepts a bytes object rather than a str, and does
817 not perform string-to-bytes encoding. It always returns an ASCII string.
Senthil Kumaranffa4b2c2012-05-26 09:53:32 +0800818 quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000819 """
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000820 if not isinstance(bs, (bytes, bytearray)):
821 raise TypeError("quote_from_bytes() expected bytes")
822 if not bs:
823 return ''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000824 if isinstance(safe, str):
825 # Normalize 'safe' by converting to bytes and removing non-ASCII chars
826 safe = safe.encode('ascii', 'ignore')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000827 else:
828 safe = bytes([c for c in safe if c < 128])
829 if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
830 return bs.decode()
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000831 try:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000832 quoter = _safe_quoters[safe]
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000833 except KeyError:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000834 _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
835 return ''.join([quoter(char) for char in bs])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000836
R David Murrayc17686f2015-05-17 20:44:50 -0400837def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
838 quote_via=quote_plus):
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700839 """Encode a dict or sequence of two-element tuples into a URL query string.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000840
841 If any values in the query arg are sequences and doseq is true, each
842 sequence element is converted to a separate parameter.
843
844 If the query arg is a sequence of two-element tuples, the order of the
845 parameters in the output will match the order of parameters in the
846 input.
Senthil Kumarandf022da2010-07-03 17:48:22 +0000847
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700848 The components of a query arg may each be either a string or a bytes type.
R David Murray8c4e1122014-12-24 21:23:18 -0500849
R David Murrayc17686f2015-05-17 20:44:50 -0400850 The safe, encoding, and errors parameters are passed down to the function
851 specified by quote_via (encoding and errors only if a component is a str).
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000852 """
853
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000854 if hasattr(query, "items"):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000855 query = query.items()
856 else:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000857 # It's a bother at times that strings and string-like objects are
858 # sequences.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000859 try:
860 # non-sequence items should not work with len()
861 # non-empty strings will fail this
862 if len(query) and not isinstance(query[0], tuple):
863 raise TypeError
Jeremy Hylton230feba2009-03-26 16:56:59 +0000864 # Zero-length sequences of all types will get here and succeed,
865 # but that's a minor nit. Since the original implementation
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000866 # allowed empty dicts that type of behavior probably should be
867 # preserved for consistency
868 except TypeError:
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000869 ty, va, tb = sys.exc_info()
870 raise TypeError("not a valid non-string sequence "
871 "or mapping object").with_traceback(tb)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000872
873 l = []
874 if not doseq:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000875 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000876 if isinstance(k, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400877 k = quote_via(k, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000878 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400879 k = quote_via(str(k), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000880
881 if isinstance(v, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400882 v = quote_via(v, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000883 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400884 v = quote_via(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000885 l.append(k + '=' + v)
886 else:
887 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000888 if isinstance(k, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400889 k = quote_via(k, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000890 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400891 k = quote_via(str(k), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000892
893 if isinstance(v, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400894 v = quote_via(v, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000895 l.append(k + '=' + v)
896 elif isinstance(v, str):
R David Murrayc17686f2015-05-17 20:44:50 -0400897 v = quote_via(v, safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000898 l.append(k + '=' + v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000899 else:
900 try:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000901 # Is this a sufficient test for sequence-ness?
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000902 x = len(v)
903 except TypeError:
904 # not a sequence
R David Murrayc17686f2015-05-17 20:44:50 -0400905 v = quote_via(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000906 l.append(k + '=' + v)
907 else:
908 # loop over the sequence
909 for elt in v:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000910 if isinstance(elt, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400911 elt = quote_via(elt, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000912 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400913 elt = quote_via(str(elt), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000914 l.append(k + '=' + elt)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000915 return '&'.join(l)
916
Cheryl Sabella0250de42018-04-25 16:51:54 -0700917
Georg Brandl13e89462008-07-01 19:56:00 +0000918def to_bytes(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700919 warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",
920 DeprecationWarning, stacklevel=2)
921 return _to_bytes(url)
922
923
924def _to_bytes(url):
Georg Brandl13e89462008-07-01 19:56:00 +0000925 """to_bytes(u"URL") --> 'URL'."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000926 # Most URL schemes require ASCII. If that changes, the conversion
927 # can be relaxed.
Georg Brandl13e89462008-07-01 19:56:00 +0000928 # XXX get rid of to_bytes()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000929 if isinstance(url, str):
930 try:
931 url = url.encode("ASCII").decode()
932 except UnicodeError:
933 raise UnicodeError("URL " + repr(url) +
934 " contains non-ASCII characters")
935 return url
936
Cheryl Sabella0250de42018-04-25 16:51:54 -0700937
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000938def unwrap(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700939 warnings.warn("urllib.parse.unwrap() is deprecated as of 3.8",
940 DeprecationWarning, stacklevel=2)
941 return _unwrap(url)
942
943
944def _unwrap(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000945 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
946 url = str(url).strip()
947 if url[:1] == '<' and url[-1:] == '>':
948 url = url[1:-1].strip()
949 if url[:4] == 'URL:': url = url[4:].strip()
950 return url
951
Cheryl Sabella0250de42018-04-25 16:51:54 -0700952
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000953def splittype(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700954 warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, "
955 "use urllib.parse.urlparse() instead",
956 DeprecationWarning, stacklevel=2)
957 return _splittype(url)
958
959
960_typeprog = None
961def _splittype(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000962 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
963 global _typeprog
964 if _typeprog is None:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200965 _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000966
967 match = _typeprog.match(url)
968 if match:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200969 scheme, data = match.groups()
970 return scheme.lower(), data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000971 return None, url
972
Cheryl Sabella0250de42018-04-25 16:51:54 -0700973
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000974def splithost(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700975 warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, "
976 "use urllib.parse.urlparse() instead",
977 DeprecationWarning, stacklevel=2)
978 return _splithost(url)
979
980
981_hostprog = None
982def _splithost(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000983 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
984 global _hostprog
985 if _hostprog is None:
postmasters90e01e52017-06-20 06:02:44 -0700986 _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000987
988 match = _hostprog.match(url)
Senthil Kumaranc2958622010-11-22 04:48:26 +0000989 if match:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200990 host_port, path = match.groups()
991 if path and path[0] != '/':
Senthil Kumaranc2958622010-11-22 04:48:26 +0000992 path = '/' + path
993 return host_port, path
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000994 return None, url
995
Cheryl Sabella0250de42018-04-25 16:51:54 -0700996
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000997def splituser(host):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700998 warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, "
999 "use urllib.parse.urlparse() instead",
1000 DeprecationWarning, stacklevel=2)
1001 return _splituser(host)
1002
1003
1004def _splituser(host):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001005 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001006 user, delim, host = host.rpartition('@')
1007 return (user if delim else None), host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001008
Cheryl Sabella0250de42018-04-25 16:51:54 -07001009
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001010def splitpasswd(user):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001011 warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, "
1012 "use urllib.parse.urlparse() instead",
1013 DeprecationWarning, stacklevel=2)
1014 return _splitpasswd(user)
1015
1016
1017def _splitpasswd(user):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001018 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001019 user, delim, passwd = user.partition(':')
1020 return user, (passwd if delim else None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001021
Cheryl Sabella0250de42018-04-25 16:51:54 -07001022
1023def splitport(host):
1024 warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, "
1025 "use urllib.parse.urlparse() instead",
1026 DeprecationWarning, stacklevel=2)
1027 return _splitport(host)
1028
1029
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001030# splittag('/path#tag') --> '/path', 'tag'
1031_portprog = None
Cheryl Sabella0250de42018-04-25 16:51:54 -07001032def _splitport(host):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033 """splitport('host:port') --> 'host', 'port'."""
1034 global _portprog
1035 if _portprog is None:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001036 _portprog = re.compile('(.*):([0-9]*)$', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001037
1038 match = _portprog.match(host)
Serhiy Storchakaff97b082014-01-18 18:30:33 +02001039 if match:
1040 host, port = match.groups()
1041 if port:
1042 return host, port
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001043 return host, None
1044
Cheryl Sabella0250de42018-04-25 16:51:54 -07001045
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001046def splitnport(host, defport=-1):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001047 warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, "
1048 "use urllib.parse.urlparse() instead",
1049 DeprecationWarning, stacklevel=2)
1050 return _splitnport(host, defport)
1051
1052
1053def _splitnport(host, defport=-1):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001054 """Split host and port, returning numeric port.
1055 Return given default port if no ':' found; defaults to -1.
1056 Return numerical port if a valid number are found after ':'.
1057 Return None if ':' but not a valid number."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001058 host, delim, port = host.rpartition(':')
1059 if not delim:
1060 host = port
1061 elif port:
1062 try:
1063 nport = int(port)
1064 except ValueError:
1065 nport = None
1066 return host, nport
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001067 return host, defport
1068
Cheryl Sabella0250de42018-04-25 16:51:54 -07001069
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001070def splitquery(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001071 warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, "
1072 "use urllib.parse.urlparse() instead",
1073 DeprecationWarning, stacklevel=2)
1074 return _splitquery(url)
1075
1076
1077def _splitquery(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001078 """splitquery('/path?query') --> '/path', 'query'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001079 path, delim, query = url.rpartition('?')
1080 if delim:
1081 return path, query
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001082 return url, None
1083
Cheryl Sabella0250de42018-04-25 16:51:54 -07001084
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001085def splittag(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001086 warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, "
1087 "use urllib.parse.urlparse() instead",
1088 DeprecationWarning, stacklevel=2)
1089 return _splittag(url)
1090
1091
1092def _splittag(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001093 """splittag('/path#tag') --> '/path', 'tag'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001094 path, delim, tag = url.rpartition('#')
1095 if delim:
1096 return path, tag
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001097 return url, None
1098
Cheryl Sabella0250de42018-04-25 16:51:54 -07001099
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001100def splitattr(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001101 warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, "
1102 "use urllib.parse.urlparse() instead",
1103 DeprecationWarning, stacklevel=2)
1104 return _splitattr(url)
1105
1106
1107def _splitattr(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001108 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1109 '/path', ['attr1=value1', 'attr2=value2', ...]."""
1110 words = url.split(';')
1111 return words[0], words[1:]
1112
Cheryl Sabella0250de42018-04-25 16:51:54 -07001113
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001114def splitvalue(attr):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001115 warnings.warn("urllib.parse.splitvalue() is deprecated as of 3.8, "
1116 "use urllib.parse.parse_qsl() instead",
1117 DeprecationWarning, stacklevel=2)
1118 return _splitvalue(attr)
1119
1120
1121def _splitvalue(attr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001122 """splitvalue('attr=value') --> 'attr', 'value'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001123 attr, delim, value = attr.partition('=')
1124 return attr, (value if delim else None)