blob: 8b6c9b10609152966263c8c880527ebbd0924c7c [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
Steve Dower16e6f7d2019-03-07 08:02:26 -0800399def _checknetloc(netloc):
400 if not netloc or netloc.isascii():
401 return
402 # looking for characters like \u2100 that expand to 'a/c'
403 # IDNA uses NFKC equivalence, so normalize for this check
404 import unicodedata
405 netloc2 = unicodedata.normalize('NFKC', netloc)
406 if netloc == netloc2:
407 return
408 _, _, netloc = netloc.rpartition('@') # anything to the left of '@' is okay
409 for c in '/?#@:':
410 if c in netloc2:
411 raise ValueError("netloc '" + netloc2 + "' contains invalid " +
412 "characters under NFKC normalization")
413
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000414def urlsplit(url, scheme='', allow_fragments=True):
415 """Parse a URL into 5 components:
416 <scheme>://<netloc>/<path>?<query>#<fragment>
417 Return a 5-tuple: (scheme, netloc, path, query, fragment).
418 Note that we don't break the components up in smaller bits
419 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000420 url, scheme, _coerce_result = _coerce_args(url, scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000421 allow_fragments = bool(allow_fragments)
422 key = url, scheme, allow_fragments, type(url), type(scheme)
423 cached = _parse_cache.get(key, None)
424 if cached:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000425 return _coerce_result(cached)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000426 if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
427 clear_cache()
428 netloc = query = fragment = ''
429 i = url.find(':')
430 if i > 0:
431 if url[:i] == 'http': # optimize the common case
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000432 url = url[i+1:]
433 if url[:2] == '//':
434 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000435 if (('[' in netloc and ']' not in netloc) or
436 (']' in netloc and '[' not in netloc)):
437 raise ValueError("Invalid IPv6 URL")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000438 if allow_fragments and '#' in url:
439 url, fragment = url.split('#', 1)
440 if '?' in url:
441 url, query = url.split('?', 1)
Steve Dower16e6f7d2019-03-07 08:02:26 -0800442 _checknetloc(netloc)
Oren Milman8df44ee2017-09-03 07:51:39 +0300443 v = SplitResult('http', netloc, url, query, fragment)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000444 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000445 return _coerce_result(v)
Senthil Kumaran397eb442011-04-15 18:20:24 +0800446 for c in url[:i]:
447 if c not in scheme_chars:
448 break
449 else:
Ezio Melotti6709b7d2012-05-19 17:15:19 +0300450 # make sure "url" is not actually a port number (in which case
451 # "scheme" is really part of the path)
452 rest = url[i+1:]
453 if not rest or any(c not in '0123456789' for c in rest):
454 # not a port number
455 scheme, url = url[:i].lower(), rest
Senthil Kumaran397eb442011-04-15 18:20:24 +0800456
Senthil Kumaran6be85c52010-02-19 07:42:50 +0000457 if url[:2] == '//':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000458 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000459 if (('[' in netloc and ']' not in netloc) or
460 (']' in netloc and '[' not in netloc)):
461 raise ValueError("Invalid IPv6 URL")
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800462 if allow_fragments and '#' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000463 url, fragment = url.split('#', 1)
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800464 if '?' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000465 url, query = url.split('?', 1)
Steve Dower16e6f7d2019-03-07 08:02:26 -0800466 _checknetloc(netloc)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000467 v = SplitResult(scheme, netloc, url, query, fragment)
468 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000469 return _coerce_result(v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000470
471def urlunparse(components):
472 """Put a parsed URL back together again. This may result in a
473 slightly different, but equivalent URL, if the URL that was parsed
474 originally had redundant delimiters, e.g. a ? with an empty query
475 (the draft states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000476 scheme, netloc, url, params, query, fragment, _coerce_result = (
477 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000478 if params:
479 url = "%s;%s" % (url, params)
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000480 return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000481
482def urlunsplit(components):
Senthil Kumaran8749a632010-06-28 14:08:00 +0000483 """Combine the elements of a tuple as returned by urlsplit() into a
484 complete URL as a string. The data argument can be any five-item iterable.
485 This may result in a slightly different, but equivalent URL, if the URL that
486 was parsed originally had unnecessary delimiters (for example, a ? with an
487 empty query; the RFC states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000488 scheme, netloc, url, query, fragment, _coerce_result = (
489 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000490 if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
491 if url and url[:1] != '/': url = '/' + url
492 url = '//' + (netloc or '') + url
493 if scheme:
494 url = scheme + ':' + url
495 if query:
496 url = url + '?' + query
497 if fragment:
498 url = url + '#' + fragment
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000499 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000500
501def urljoin(base, url, allow_fragments=True):
502 """Join a base URL and a possibly relative URL to form an absolute
503 interpretation of the latter."""
504 if not base:
505 return url
506 if not url:
507 return base
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400508
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000509 base, url, _coerce_result = _coerce_args(base, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000510 bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
511 urlparse(base, '', allow_fragments)
512 scheme, netloc, path, params, query, fragment = \
513 urlparse(url, bscheme, allow_fragments)
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400514
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000515 if scheme != bscheme or scheme not in uses_relative:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000516 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000517 if scheme in uses_netloc:
518 if netloc:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000519 return _coerce_result(urlunparse((scheme, netloc, path,
520 params, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000521 netloc = bnetloc
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400522
Senthil Kumarandca5b862010-12-17 04:48:45 +0000523 if not path and not params:
Facundo Batista23e38562008-08-14 16:55:14 +0000524 path = bpath
Senthil Kumarandca5b862010-12-17 04:48:45 +0000525 params = bparams
Facundo Batista23e38562008-08-14 16:55:14 +0000526 if not query:
527 query = bquery
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000528 return _coerce_result(urlunparse((scheme, netloc, path,
529 params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400530
531 base_parts = bpath.split('/')
532 if base_parts[-1] != '':
533 # the last item is not a directory, so will not be taken into account
534 # in resolving the relative path
535 del base_parts[-1]
536
537 # for rfc3986, ignore all base path should the first character be root.
538 if path[:1] == '/':
539 segments = path.split('/')
540 else:
541 segments = base_parts + path.split('/')
Senthil Kumarana66e3882014-09-22 15:49:16 +0800542 # filter out elements that would cause redundant slashes on re-joining
543 # the resolved_path
Berker Peksag20416f72015-04-16 02:31:14 +0300544 segments[1:-1] = filter(None, segments[1:-1])
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400545
546 resolved_path = []
547
548 for seg in segments:
549 if seg == '..':
550 try:
551 resolved_path.pop()
552 except IndexError:
553 # ignore any .. segments that would otherwise cause an IndexError
554 # when popped from resolved_path if resolving for rfc3986
555 pass
556 elif seg == '.':
557 continue
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000558 else:
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400559 resolved_path.append(seg)
560
561 if segments[-1] in ('.', '..'):
562 # do some post-processing here. if the last segment was a relative dir,
563 # then we need to append the trailing '/'
564 resolved_path.append('')
565
566 return _coerce_result(urlunparse((scheme, netloc, '/'.join(
Senthil Kumarana66e3882014-09-22 15:49:16 +0800567 resolved_path) or '/', params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400568
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000569
570def urldefrag(url):
571 """Removes any existing fragment from URL.
572
573 Returns a tuple of the defragmented URL and the fragment. If
574 the URL contained no fragments, the second element is the
575 empty string.
576 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000577 url, _coerce_result = _coerce_args(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000578 if '#' in url:
579 s, n, p, a, q, frag = urlparse(url)
580 defrag = urlunparse((s, n, p, a, q, ''))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000581 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000582 frag = ''
583 defrag = url
584 return _coerce_result(DefragResult(defrag, frag))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000585
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200586_hexdig = '0123456789ABCDEFabcdef'
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100587_hextobyte = None
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200588
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000589def unquote_to_bytes(string):
590 """unquote_to_bytes('abc%20def') -> b'abc def'."""
591 # Note: strings are encoded as UTF-8. This is only an issue if it contains
592 # unescaped non-ASCII characters, which URIs should not.
Florent Xicluna82a3f8a2010-08-14 18:30:35 +0000593 if not string:
594 # Is it a string-like object?
595 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000596 return b''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000597 if isinstance(string, str):
598 string = string.encode('utf-8')
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200599 bits = string.split(b'%')
600 if len(bits) == 1:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000601 return string
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200602 res = [bits[0]]
603 append = res.append
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100604 # Delay the initialization of the table to not waste memory
605 # if the function is never called
606 global _hextobyte
607 if _hextobyte is None:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +0200608 _hextobyte = {(a + b).encode(): bytes.fromhex(a + b)
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100609 for a in _hexdig for b in _hexdig}
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200610 for item in bits[1:]:
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000611 try:
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200612 append(_hextobyte[item[:2]])
613 append(item[2:])
614 except KeyError:
615 append(b'%')
616 append(item)
617 return b''.join(res)
618
619_asciire = re.compile('([\x00-\x7f]+)')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000620
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000621def unquote(string, encoding='utf-8', errors='replace'):
622 """Replace %xx escapes by their single-character equivalent. The optional
623 encoding and errors parameters specify how to decode percent-encoded
624 sequences into Unicode characters, as accepted by the bytes.decode()
625 method.
626 By default, percent-encoded sequences are decoded with UTF-8, and invalid
627 sequences are replaced by a placeholder character.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000628
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000629 unquote('abc%20def') -> 'abc def'.
630 """
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200631 if '%' not in string:
632 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000633 return string
634 if encoding is None:
635 encoding = 'utf-8'
636 if errors is None:
637 errors = 'replace'
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200638 bits = _asciire.split(string)
639 res = [bits[0]]
640 append = res.append
641 for i in range(1, len(bits), 2):
642 append(unquote_to_bytes(bits[i]).decode(encoding, errors))
643 append(bits[i + 1])
644 return ''.join(res)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000645
Senthil Kumaran257b9802017-04-04 21:19:43 -0700646
Victor Stinnerac71c542011-01-14 12:52:12 +0000647def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
matthewbelisle-wf20914482018-10-19 05:52:59 -0500648 encoding='utf-8', errors='replace', max_num_fields=None):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000649 """Parse a query given as a string argument.
650
651 Arguments:
652
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000653 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000654
655 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000656 percent-encoded queries should be treated as blank strings.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000657 A true value indicates that blanks should be retained as
658 blank strings. The default false value indicates that
659 blank values are to be ignored and treated as if they were
660 not included.
661
662 strict_parsing: flag indicating what to do with parsing errors.
663 If false (the default), errors are silently ignored.
664 If true, errors raise a ValueError exception.
Victor Stinnerac71c542011-01-14 12:52:12 +0000665
666 encoding and errors: specify how to decode percent-encoded sequences
667 into Unicode characters, as accepted by the bytes.decode() method.
Senthil Kumaran257b9802017-04-04 21:19:43 -0700668
matthewbelisle-wf20914482018-10-19 05:52:59 -0500669 max_num_fields: int. If set, then throws a ValueError if there
670 are more than n fields read by parse_qsl().
671
Senthil Kumaran257b9802017-04-04 21:19:43 -0700672 Returns a dictionary.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000673 """
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700674 parsed_result = {}
Victor Stinnerac71c542011-01-14 12:52:12 +0000675 pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
matthewbelisle-wf20914482018-10-19 05:52:59 -0500676 encoding=encoding, errors=errors,
677 max_num_fields=max_num_fields)
Victor Stinnerac71c542011-01-14 12:52:12 +0000678 for name, value in pairs:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700679 if name in parsed_result:
680 parsed_result[name].append(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000681 else:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700682 parsed_result[name] = [value]
683 return parsed_result
Facundo Batistac469d4c2008-09-03 22:49:01 +0000684
Senthil Kumaran257b9802017-04-04 21:19:43 -0700685
Victor Stinnerac71c542011-01-14 12:52:12 +0000686def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
matthewbelisle-wf20914482018-10-19 05:52:59 -0500687 encoding='utf-8', errors='replace', max_num_fields=None):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000688 """Parse a query given as a string argument.
689
Senthil Kumaran257b9802017-04-04 21:19:43 -0700690 Arguments:
Facundo Batistac469d4c2008-09-03 22:49:01 +0000691
Senthil Kumaran257b9802017-04-04 21:19:43 -0700692 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000693
Senthil Kumaran257b9802017-04-04 21:19:43 -0700694 keep_blank_values: flag indicating whether blank values in
695 percent-encoded queries should be treated as blank strings.
696 A true value indicates that blanks should be retained as blank
697 strings. The default false value indicates that blank values
698 are to be ignored and treated as if they were not included.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000699
Senthil Kumaran257b9802017-04-04 21:19:43 -0700700 strict_parsing: flag indicating what to do with parsing errors. If
701 false (the default), errors are silently ignored. If true,
702 errors raise a ValueError exception.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000703
Senthil Kumaran257b9802017-04-04 21:19:43 -0700704 encoding and errors: specify how to decode percent-encoded sequences
705 into Unicode characters, as accepted by the bytes.decode() method.
Victor Stinnerac71c542011-01-14 12:52:12 +0000706
matthewbelisle-wf20914482018-10-19 05:52:59 -0500707 max_num_fields: int. If set, then throws a ValueError
708 if there are more than n fields read by parse_qsl().
709
Senthil Kumaran257b9802017-04-04 21:19:43 -0700710 Returns a list, as G-d intended.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000711 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000712 qs, _coerce_result = _coerce_args(qs)
matthewbelisle-wf20914482018-10-19 05:52:59 -0500713
714 # If max_num_fields is defined then check that the number of fields
715 # is less than max_num_fields. This prevents a memory exhaustion DOS
716 # attack via post bodies with many fields.
717 if max_num_fields is not None:
718 num_fields = 1 + qs.count('&') + qs.count(';')
719 if max_num_fields < num_fields:
720 raise ValueError('Max number of fields exceeded')
721
Facundo Batistac469d4c2008-09-03 22:49:01 +0000722 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
723 r = []
724 for name_value in pairs:
725 if not name_value and not strict_parsing:
726 continue
727 nv = name_value.split('=', 1)
728 if len(nv) != 2:
729 if strict_parsing:
730 raise ValueError("bad query field: %r" % (name_value,))
731 # Handle case of a control-name with no equal sign
732 if keep_blank_values:
733 nv.append('')
734 else:
735 continue
736 if len(nv[1]) or keep_blank_values:
Victor Stinnerac71c542011-01-14 12:52:12 +0000737 name = nv[0].replace('+', ' ')
738 name = unquote(name, encoding=encoding, errors=errors)
739 name = _coerce_result(name)
740 value = nv[1].replace('+', ' ')
741 value = unquote(value, encoding=encoding, errors=errors)
742 value = _coerce_result(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000743 r.append((name, value))
Facundo Batistac469d4c2008-09-03 22:49:01 +0000744 return r
745
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000746def unquote_plus(string, encoding='utf-8', errors='replace'):
747 """Like unquote(), but also replace plus signs by spaces, as required for
748 unquoting HTML form values.
749
750 unquote_plus('%7e/abc+def') -> '~/abc def'
751 """
752 string = string.replace('+', ' ')
753 return unquote(string, encoding, errors)
754
755_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
756 b'abcdefghijklmnopqrstuvwxyz'
757 b'0123456789'
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530758 b'_.-~')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000759_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
760_safe_quoters = {}
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000761
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000762class Quoter(collections.defaultdict):
763 """A mapping from bytes (in range(0,256)) to strings.
764
765 String values are percent-encoded byte values, unless the key < 128, and
766 in the "safe" set (either the specified safe set, or default set).
767 """
768 # Keeps a cache internally, using defaultdict, for efficiency (lookups
769 # of cached keys don't call Python code at all).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000770 def __init__(self, safe):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000771 """safe: bytes object."""
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000772 self.safe = _ALWAYS_SAFE.union(safe)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000773
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000774 def __repr__(self):
775 # Without this, will just display as a defaultdict
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300776 return "<%s %r>" % (self.__class__.__name__, dict(self))
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000777
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000778 def __missing__(self, b):
779 # Handle a cache miss. Store quoted string in cache and return.
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000780 res = chr(b) if b in self.safe else '%{:02X}'.format(b)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000781 self[b] = res
782 return res
783
784def quote(string, safe='/', encoding=None, errors=None):
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000785 """quote('abc def') -> 'abc%20def'
786
787 Each part of a URL, e.g. the path info, the query, etc., has a
788 different set of reserved characters that must be quoted.
789
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530790 RFC 3986 Uniform Resource Identifiers (URI): Generic Syntax lists
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000791 the following reserved characters.
792
793 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530794 "$" | "," | "~"
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000795
796 Each of these characters is reserved in some component of a URL,
797 but not necessarily in all of them.
798
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530799 Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
800 Now, "~" is included in the set of reserved characters.
801
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000802 By default, the quote function is intended for quoting the path
803 section of a URL. Thus, it will not encode '/'. This character
804 is reserved, but in typical usage the quote function is being
805 called on a path where the existing slash characters are used as
806 reserved characters.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000807
R David Murray8c4e1122014-12-24 21:23:18 -0500808 string and safe may be either str or bytes objects. encoding and errors
809 must not be specified if string is a bytes object.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000810
811 The optional encoding and errors parameters specify how to deal with
812 non-ASCII characters, as accepted by the str.encode method.
813 By default, encoding='utf-8' (characters are encoded with UTF-8), and
814 errors='strict' (unsupported characters raise a UnicodeEncodeError).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000815 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000816 if isinstance(string, str):
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000817 if not string:
818 return string
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000819 if encoding is None:
820 encoding = 'utf-8'
821 if errors is None:
822 errors = 'strict'
823 string = string.encode(encoding, errors)
824 else:
825 if encoding is not None:
826 raise TypeError("quote() doesn't support 'encoding' for bytes")
827 if errors is not None:
828 raise TypeError("quote() doesn't support 'errors' for bytes")
829 return quote_from_bytes(string, safe)
830
831def quote_plus(string, safe='', encoding=None, errors=None):
832 """Like quote(), but also replace ' ' with '+', as required for quoting
833 HTML form values. Plus signs in the original string are escaped unless
834 they are included in safe. It also does not have safe default to '/'.
835 """
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000836 # Check if ' ' in string, where string may either be a str or bytes. If
837 # there are no spaces, the regular quote will produce the right answer.
838 if ((isinstance(string, str) and ' ' not in string) or
839 (isinstance(string, bytes) and b' ' not in string)):
840 return quote(string, safe, encoding, errors)
841 if isinstance(safe, str):
842 space = ' '
843 else:
844 space = b' '
Georg Brandlfaf41492009-05-26 18:31:11 +0000845 string = quote(string, safe + space, encoding, errors)
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000846 return string.replace(' ', '+')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000847
848def quote_from_bytes(bs, safe='/'):
849 """Like quote(), but accepts a bytes object rather than a str, and does
850 not perform string-to-bytes encoding. It always returns an ASCII string.
Senthil Kumaranffa4b2c2012-05-26 09:53:32 +0800851 quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000852 """
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000853 if not isinstance(bs, (bytes, bytearray)):
854 raise TypeError("quote_from_bytes() expected bytes")
855 if not bs:
856 return ''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000857 if isinstance(safe, str):
858 # Normalize 'safe' by converting to bytes and removing non-ASCII chars
859 safe = safe.encode('ascii', 'ignore')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000860 else:
861 safe = bytes([c for c in safe if c < 128])
862 if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
863 return bs.decode()
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000864 try:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000865 quoter = _safe_quoters[safe]
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000866 except KeyError:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000867 _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
868 return ''.join([quoter(char) for char in bs])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000869
R David Murrayc17686f2015-05-17 20:44:50 -0400870def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
871 quote_via=quote_plus):
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700872 """Encode a dict or sequence of two-element tuples into a URL query string.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000873
874 If any values in the query arg are sequences and doseq is true, each
875 sequence element is converted to a separate parameter.
876
877 If the query arg is a sequence of two-element tuples, the order of the
878 parameters in the output will match the order of parameters in the
879 input.
Senthil Kumarandf022da2010-07-03 17:48:22 +0000880
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700881 The components of a query arg may each be either a string or a bytes type.
R David Murray8c4e1122014-12-24 21:23:18 -0500882
R David Murrayc17686f2015-05-17 20:44:50 -0400883 The safe, encoding, and errors parameters are passed down to the function
884 specified by quote_via (encoding and errors only if a component is a str).
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000885 """
886
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000887 if hasattr(query, "items"):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000888 query = query.items()
889 else:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000890 # It's a bother at times that strings and string-like objects are
891 # sequences.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000892 try:
893 # non-sequence items should not work with len()
894 # non-empty strings will fail this
895 if len(query) and not isinstance(query[0], tuple):
896 raise TypeError
Jeremy Hylton230feba2009-03-26 16:56:59 +0000897 # Zero-length sequences of all types will get here and succeed,
898 # but that's a minor nit. Since the original implementation
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000899 # allowed empty dicts that type of behavior probably should be
900 # preserved for consistency
901 except TypeError:
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000902 ty, va, tb = sys.exc_info()
903 raise TypeError("not a valid non-string sequence "
904 "or mapping object").with_traceback(tb)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000905
906 l = []
907 if not doseq:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000908 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000909 if isinstance(k, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400910 k = quote_via(k, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000911 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400912 k = quote_via(str(k), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000913
914 if isinstance(v, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400915 v = quote_via(v, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000916 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400917 v = quote_via(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000918 l.append(k + '=' + v)
919 else:
920 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000921 if isinstance(k, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400922 k = quote_via(k, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000923 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400924 k = quote_via(str(k), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000925
926 if isinstance(v, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400927 v = quote_via(v, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000928 l.append(k + '=' + v)
929 elif isinstance(v, str):
R David Murrayc17686f2015-05-17 20:44:50 -0400930 v = quote_via(v, safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000931 l.append(k + '=' + v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000932 else:
933 try:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000934 # Is this a sufficient test for sequence-ness?
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000935 x = len(v)
936 except TypeError:
937 # not a sequence
R David Murrayc17686f2015-05-17 20:44:50 -0400938 v = quote_via(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000939 l.append(k + '=' + v)
940 else:
941 # loop over the sequence
942 for elt in v:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000943 if isinstance(elt, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400944 elt = quote_via(elt, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000945 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400946 elt = quote_via(str(elt), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000947 l.append(k + '=' + elt)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000948 return '&'.join(l)
949
Cheryl Sabella0250de42018-04-25 16:51:54 -0700950
Georg Brandl13e89462008-07-01 19:56:00 +0000951def to_bytes(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700952 warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",
953 DeprecationWarning, stacklevel=2)
954 return _to_bytes(url)
955
956
957def _to_bytes(url):
Georg Brandl13e89462008-07-01 19:56:00 +0000958 """to_bytes(u"URL") --> 'URL'."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000959 # Most URL schemes require ASCII. If that changes, the conversion
960 # can be relaxed.
Georg Brandl13e89462008-07-01 19:56:00 +0000961 # XXX get rid of to_bytes()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000962 if isinstance(url, str):
963 try:
964 url = url.encode("ASCII").decode()
965 except UnicodeError:
966 raise UnicodeError("URL " + repr(url) +
967 " contains non-ASCII characters")
968 return url
969
Cheryl Sabella0250de42018-04-25 16:51:54 -0700970
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000971def unwrap(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700972 warnings.warn("urllib.parse.unwrap() is deprecated as of 3.8",
973 DeprecationWarning, stacklevel=2)
974 return _unwrap(url)
975
976
977def _unwrap(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000978 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
979 url = str(url).strip()
980 if url[:1] == '<' and url[-1:] == '>':
981 url = url[1:-1].strip()
982 if url[:4] == 'URL:': url = url[4:].strip()
983 return url
984
Cheryl Sabella0250de42018-04-25 16:51:54 -0700985
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000986def splittype(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -0700987 warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, "
988 "use urllib.parse.urlparse() instead",
989 DeprecationWarning, stacklevel=2)
990 return _splittype(url)
991
992
993_typeprog = None
994def _splittype(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000995 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
996 global _typeprog
997 if _typeprog is None:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200998 _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000999
1000 match = _typeprog.match(url)
1001 if match:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001002 scheme, data = match.groups()
1003 return scheme.lower(), data
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001004 return None, url
1005
Cheryl Sabella0250de42018-04-25 16:51:54 -07001006
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001007def splithost(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001008 warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, "
1009 "use urllib.parse.urlparse() instead",
1010 DeprecationWarning, stacklevel=2)
1011 return _splithost(url)
1012
1013
1014_hostprog = None
1015def _splithost(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001016 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
1017 global _hostprog
1018 if _hostprog is None:
postmasters90e01e52017-06-20 06:02:44 -07001019 _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001020
1021 match = _hostprog.match(url)
Senthil Kumaranc2958622010-11-22 04:48:26 +00001022 if match:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001023 host_port, path = match.groups()
1024 if path and path[0] != '/':
Senthil Kumaranc2958622010-11-22 04:48:26 +00001025 path = '/' + path
1026 return host_port, path
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001027 return None, url
1028
Cheryl Sabella0250de42018-04-25 16:51:54 -07001029
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001030def splituser(host):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001031 warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, "
1032 "use urllib.parse.urlparse() instead",
1033 DeprecationWarning, stacklevel=2)
1034 return _splituser(host)
1035
1036
1037def _splituser(host):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001038 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001039 user, delim, host = host.rpartition('@')
1040 return (user if delim else None), host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001041
Cheryl Sabella0250de42018-04-25 16:51:54 -07001042
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001043def splitpasswd(user):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001044 warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, "
1045 "use urllib.parse.urlparse() instead",
1046 DeprecationWarning, stacklevel=2)
1047 return _splitpasswd(user)
1048
1049
1050def _splitpasswd(user):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001051 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001052 user, delim, passwd = user.partition(':')
1053 return user, (passwd if delim else None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001054
Cheryl Sabella0250de42018-04-25 16:51:54 -07001055
1056def splitport(host):
1057 warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, "
1058 "use urllib.parse.urlparse() instead",
1059 DeprecationWarning, stacklevel=2)
1060 return _splitport(host)
1061
1062
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001063# splittag('/path#tag') --> '/path', 'tag'
1064_portprog = None
Cheryl Sabella0250de42018-04-25 16:51:54 -07001065def _splitport(host):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001066 """splitport('host:port') --> 'host', 'port'."""
1067 global _portprog
1068 if _portprog is None:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001069 _portprog = re.compile('(.*):([0-9]*)$', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001070
1071 match = _portprog.match(host)
Serhiy Storchakaff97b082014-01-18 18:30:33 +02001072 if match:
1073 host, port = match.groups()
1074 if port:
1075 return host, port
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001076 return host, None
1077
Cheryl Sabella0250de42018-04-25 16:51:54 -07001078
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001079def splitnport(host, defport=-1):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001080 warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, "
1081 "use urllib.parse.urlparse() instead",
1082 DeprecationWarning, stacklevel=2)
1083 return _splitnport(host, defport)
1084
1085
1086def _splitnport(host, defport=-1):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001087 """Split host and port, returning numeric port.
1088 Return given default port if no ':' found; defaults to -1.
1089 Return numerical port if a valid number are found after ':'.
1090 Return None if ':' but not a valid number."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001091 host, delim, port = host.rpartition(':')
1092 if not delim:
1093 host = port
1094 elif port:
1095 try:
1096 nport = int(port)
1097 except ValueError:
1098 nport = None
1099 return host, nport
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001100 return host, defport
1101
Cheryl Sabella0250de42018-04-25 16:51:54 -07001102
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001103def splitquery(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001104 warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, "
1105 "use urllib.parse.urlparse() instead",
1106 DeprecationWarning, stacklevel=2)
1107 return _splitquery(url)
1108
1109
1110def _splitquery(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001111 """splitquery('/path?query') --> '/path', 'query'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001112 path, delim, query = url.rpartition('?')
1113 if delim:
1114 return path, query
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001115 return url, None
1116
Cheryl Sabella0250de42018-04-25 16:51:54 -07001117
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001118def splittag(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001119 warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, "
1120 "use urllib.parse.urlparse() instead",
1121 DeprecationWarning, stacklevel=2)
1122 return _splittag(url)
1123
1124
1125def _splittag(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001126 """splittag('/path#tag') --> '/path', 'tag'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001127 path, delim, tag = url.rpartition('#')
1128 if delim:
1129 return path, tag
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001130 return url, None
1131
Cheryl Sabella0250de42018-04-25 16:51:54 -07001132
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001133def splitattr(url):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001134 warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, "
1135 "use urllib.parse.urlparse() instead",
1136 DeprecationWarning, stacklevel=2)
1137 return _splitattr(url)
1138
1139
1140def _splitattr(url):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001141 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1142 '/path', ['attr1=value1', 'attr2=value2', ...]."""
1143 words = url.split(';')
1144 return words[0], words[1:]
1145
Cheryl Sabella0250de42018-04-25 16:51:54 -07001146
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001147def splitvalue(attr):
Cheryl Sabella0250de42018-04-25 16:51:54 -07001148 warnings.warn("urllib.parse.splitvalue() is deprecated as of 3.8, "
1149 "use urllib.parse.parse_qsl() instead",
1150 DeprecationWarning, stacklevel=2)
1151 return _splitvalue(attr)
1152
1153
1154def _splitvalue(attr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001155 """splitvalue('attr=value') --> 'attr', 'value'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001156 attr, delim, value = attr.partition('=')
1157 return attr, (value if delim else None)