blob: 01eb54906c8a53b6e9e18ea3d1e0cf10c6b84c59 [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
Facundo Batista2ac5de22008-07-07 18:24:11 +000033
Jeremy Hylton1afc1692008-06-18 20:49:58 +000034__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
Senthil Kumaran0256b2a2010-10-25 16:36:20 +000035 "urlsplit", "urlunsplit", "urlencode", "parse_qs",
36 "parse_qsl", "quote", "quote_plus", "quote_from_bytes",
Serhiy Storchaka15154502015-04-07 19:09:01 +030037 "unquote", "unquote_plus", "unquote_to_bytes",
38 "DefragResult", "ParseResult", "SplitResult",
39 "DefragResultBytes", "ParseResultBytes", "SplitResultBytes"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +000040
Senthil Kumaran906f5332017-05-17 21:48:59 -070041# A classification of schemes.
42# The empty string classifies URLs with no scheme specified,
43# being the default value returned by “urlsplit” and “urlparse”.
44
45uses_relative = ['', 'ftp', 'http', 'gopher', 'nntp', 'imap',
Jeremy Hylton1afc1692008-06-18 20:49:58 +000046 'wais', 'file', 'https', 'shttp', 'mms',
Senthil Kumaran906f5332017-05-17 21:48:59 -070047 'prospero', 'rtsp', 'rtspu', 'sftp',
Berker Peksagf6767482016-09-16 14:43:58 +030048 'svn', 'svn+ssh', 'ws', 'wss']
Senthil Kumaran906f5332017-05-17 21:48:59 -070049
50uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet',
Jeremy Hylton1afc1692008-06-18 20:49:58 +000051 'imap', 'wais', 'file', 'mms', 'https', 'shttp',
Senthil Kumaran906f5332017-05-17 21:48:59 -070052 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync',
Berker Peksagf6767482016-09-16 14:43:58 +030053 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
54 'ws', 'wss']
Senthil Kumaran906f5332017-05-17 21:48:59 -070055
56uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
Jeremy Hylton1afc1692008-06-18 20:49:58 +000057 'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
Senthil Kumaran906f5332017-05-17 21:48:59 -070058 'mms', 'sftp', 'tel']
Jeremy Hylton1afc1692008-06-18 20:49:58 +000059
Georg Brandla61b09f2012-08-24 18:15:29 +020060# These are not actually used anymore, but should stay for backwards
61# compatibility. (They are undocumented, but have a public-looking name.)
Senthil Kumaran906f5332017-05-17 21:48:59 -070062
Georg Brandla61b09f2012-08-24 18:15:29 +020063non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
64 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
Senthil Kumaran906f5332017-05-17 21:48:59 -070065
66uses_query = ['', 'http', 'wais', 'imap', 'https', 'shttp', 'mms',
67 'gopher', 'rtsp', 'rtspu', 'sip', 'sips']
68
69uses_fragment = ['', 'ftp', 'hdl', 'http', 'gopher', 'news',
Georg Brandla61b09f2012-08-24 18:15:29 +020070 'nntp', 'wais', 'https', 'shttp', 'snews',
Senthil Kumaran906f5332017-05-17 21:48:59 -070071 'file', 'prospero']
Georg Brandla61b09f2012-08-24 18:15:29 +020072
Jeremy Hylton1afc1692008-06-18 20:49:58 +000073# Characters valid in scheme names
74scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
75 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
76 '0123456789'
77 '+-.')
78
Nick Coghlan9fc443c2010-11-30 15:48:08 +000079# XXX: Consider replacing with functools.lru_cache
Jeremy Hylton1afc1692008-06-18 20:49:58 +000080MAX_CACHE_SIZE = 20
81_parse_cache = {}
82
83def clear_cache():
Antoine Pitrou2df5fc72009-12-08 19:38:17 +000084 """Clear the parse cache and the quoters cache."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +000085 _parse_cache.clear()
Antoine Pitrou2df5fc72009-12-08 19:38:17 +000086 _safe_quoters.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000087
88
Nick Coghlan9fc443c2010-11-30 15:48:08 +000089# Helpers for bytes handling
90# For 3.2, we deliberately require applications that
91# handle improperly quoted URLs to do their own
92# decoding and encoding. If valid use cases are
93# presented, we may relax this by using latin-1
94# decoding internally for 3.3
95_implicit_encoding = 'ascii'
96_implicit_errors = 'strict'
97
98def _noop(obj):
99 return obj
100
101def _encode_result(obj, encoding=_implicit_encoding,
102 errors=_implicit_errors):
103 return obj.encode(encoding, errors)
104
105def _decode_args(args, encoding=_implicit_encoding,
106 errors=_implicit_errors):
107 return tuple(x.decode(encoding, errors) if x else '' for x in args)
108
109def _coerce_args(*args):
110 # Invokes decode if necessary to create str args
111 # and returns the coerced inputs along with
112 # an appropriate result coercion function
113 # - noop for str inputs
114 # - encoding function otherwise
115 str_input = isinstance(args[0], str)
116 for arg in args[1:]:
117 # We special-case the empty string to support the
118 # "scheme=''" default argument to some functions
119 if arg and isinstance(arg, str) != str_input:
120 raise TypeError("Cannot mix str and non-str arguments")
121 if str_input:
122 return args + (_noop,)
123 return _decode_args(args) + (_encode_result,)
124
125# Result objects are more helpful than simple tuples
126class _ResultMixinStr(object):
127 """Standard approach to encoding parsed results from str to bytes"""
128 __slots__ = ()
129
130 def encode(self, encoding='ascii', errors='strict'):
131 return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
132
133
134class _ResultMixinBytes(object):
135 """Standard approach to decoding parsed results from bytes to str"""
136 __slots__ = ()
137
138 def decode(self, encoding='ascii', errors='strict'):
139 return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
140
141
142class _NetlocResultMixinBase(object):
143 """Shared methods for the parsed result objects containing a netloc element"""
144 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000145
146 @property
147 def username(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000148 return self._userinfo[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000149
150 @property
151 def password(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000152 return self._userinfo[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000153
154 @property
155 def hostname(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000156 hostname = self._hostinfo[0]
157 if not hostname:
158 hostname = None
159 elif hostname is not None:
160 hostname = hostname.lower()
161 return hostname
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000162
163 @property
164 def port(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000165 port = self._hostinfo[1]
166 if port is not None:
167 port = int(port, 10)
Senthil Kumaran2fc5a502012-05-24 21:56:17 +0800168 if not ( 0 <= port <= 65535):
Robert Collinsdfa95c92015-08-10 09:53:30 +1200169 raise ValueError("Port out of range 0-65535")
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000170 return port
171
172
173class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
174 __slots__ = ()
175
176 @property
177 def _userinfo(self):
178 netloc = self.netloc
179 userinfo, have_info, hostinfo = netloc.rpartition('@')
180 if have_info:
181 username, have_password, password = userinfo.partition(':')
182 if not have_password:
183 password = None
Senthil Kumaranad02d232010-04-16 03:02:13 +0000184 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000185 username = password = None
186 return username, password
187
188 @property
189 def _hostinfo(self):
190 netloc = self.netloc
191 _, _, hostinfo = netloc.rpartition('@')
192 _, have_open_br, bracketed = hostinfo.partition('[')
193 if have_open_br:
194 hostname, _, port = bracketed.partition(']')
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200195 _, _, port = port.partition(':')
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000196 else:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200197 hostname, _, port = hostinfo.partition(':')
198 if not port:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000199 port = None
200 return hostname, port
201
202
203class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
204 __slots__ = ()
205
206 @property
207 def _userinfo(self):
208 netloc = self.netloc
209 userinfo, have_info, hostinfo = netloc.rpartition(b'@')
210 if have_info:
211 username, have_password, password = userinfo.partition(b':')
212 if not have_password:
213 password = None
214 else:
215 username = password = None
216 return username, password
217
218 @property
219 def _hostinfo(self):
220 netloc = self.netloc
221 _, _, hostinfo = netloc.rpartition(b'@')
222 _, have_open_br, bracketed = hostinfo.partition(b'[')
223 if have_open_br:
224 hostname, _, port = bracketed.partition(b']')
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200225 _, _, port = port.partition(b':')
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000226 else:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200227 hostname, _, port = hostinfo.partition(b':')
228 if not port:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000229 port = None
230 return hostname, port
231
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000232
233from collections import namedtuple
234
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000235_DefragResultBase = namedtuple('DefragResult', 'url fragment')
Senthil Kumaran86f71092016-01-14 00:11:39 -0800236_SplitResultBase = namedtuple(
237 'SplitResult', 'scheme netloc path query fragment')
238_ParseResultBase = namedtuple(
239 'ParseResult', 'scheme netloc path params query fragment')
240
241_DefragResultBase.__doc__ = """
242DefragResult(url, fragment)
243
244A 2-tuple that contains the url without fragment identifier and the fragment
245identifier as a separate argument.
246"""
247
248_DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""
249
250_DefragResultBase.fragment.__doc__ = """
251Fragment identifier separated from URL, that allows indirect identification of a
252secondary resource by reference to a primary resource and additional identifying
253information.
254"""
255
256_SplitResultBase.__doc__ = """
257SplitResult(scheme, netloc, path, query, fragment)
258
259A 5-tuple that contains the different components of a URL. Similar to
260ParseResult, but does not split params.
261"""
262
263_SplitResultBase.scheme.__doc__ = """Specifies URL scheme for the request."""
264
265_SplitResultBase.netloc.__doc__ = """
266Network location where the request is made to.
267"""
268
269_SplitResultBase.path.__doc__ = """
270The hierarchical path, such as the path to a file to download.
271"""
272
273_SplitResultBase.query.__doc__ = """
274The query component, that contains non-hierarchical data, that along with data
275in path component, identifies a resource in the scope of URI's scheme and
276network location.
277"""
278
279_SplitResultBase.fragment.__doc__ = """
280Fragment identifier, that allows indirect identification of a secondary resource
281by reference to a primary resource and additional identifying information.
282"""
283
284_ParseResultBase.__doc__ = """
285ParseResult(scheme, netloc, path, params, query, fragment)
286
287A 6-tuple that contains components of a parsed URL.
288"""
289
290_ParseResultBase.scheme.__doc__ = _SplitResultBase.scheme.__doc__
291_ParseResultBase.netloc.__doc__ = _SplitResultBase.netloc.__doc__
292_ParseResultBase.path.__doc__ = _SplitResultBase.path.__doc__
293_ParseResultBase.params.__doc__ = """
294Parameters for last path element used to dereference the URI in order to provide
295access to perform some operation on the resource.
296"""
297
298_ParseResultBase.query.__doc__ = _SplitResultBase.query.__doc__
299_ParseResultBase.fragment.__doc__ = _SplitResultBase.fragment.__doc__
300
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000301
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000302# For backwards compatibility, alias _NetlocResultMixinStr
303# ResultBase is no longer part of the documented API, but it is
304# retained since deprecating it isn't worth the hassle
305ResultBase = _NetlocResultMixinStr
306
307# Structured result objects for string data
308class DefragResult(_DefragResultBase, _ResultMixinStr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000309 __slots__ = ()
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000310 def geturl(self):
311 if self.fragment:
312 return self.url + '#' + self.fragment
313 else:
314 return self.url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000315
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000316class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
317 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000318 def geturl(self):
319 return urlunsplit(self)
320
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000321class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000322 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000323 def geturl(self):
324 return urlunparse(self)
325
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000326# Structured result objects for bytes data
327class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
328 __slots__ = ()
329 def geturl(self):
330 if self.fragment:
331 return self.url + b'#' + self.fragment
332 else:
333 return self.url
334
335class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
336 __slots__ = ()
337 def geturl(self):
338 return urlunsplit(self)
339
340class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
341 __slots__ = ()
342 def geturl(self):
343 return urlunparse(self)
344
345# Set up the encode/decode result pairs
346def _fix_result_transcoding():
347 _result_pairs = (
348 (DefragResult, DefragResultBytes),
349 (SplitResult, SplitResultBytes),
350 (ParseResult, ParseResultBytes),
351 )
352 for _decoded, _encoded in _result_pairs:
353 _decoded._encoded_counterpart = _encoded
354 _encoded._decoded_counterpart = _decoded
355
356_fix_result_transcoding()
357del _fix_result_transcoding
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000358
359def urlparse(url, scheme='', allow_fragments=True):
360 """Parse a URL into 6 components:
361 <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
362 Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
363 Note that we don't break the components up in smaller bits
364 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000365 url, scheme, _coerce_result = _coerce_args(url, scheme)
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700366 splitresult = urlsplit(url, scheme, allow_fragments)
367 scheme, netloc, url, query, fragment = splitresult
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000368 if scheme in uses_params and ';' in url:
369 url, params = _splitparams(url)
370 else:
371 params = ''
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000372 result = ParseResult(scheme, netloc, url, params, query, fragment)
373 return _coerce_result(result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000374
375def _splitparams(url):
376 if '/' in url:
377 i = url.find(';', url.rfind('/'))
378 if i < 0:
379 return url, ''
380 else:
381 i = url.find(';')
382 return url[:i], url[i+1:]
383
384def _splitnetloc(url, start=0):
385 delim = len(url) # position of end of domain part of url, default is end
386 for c in '/?#': # look for delimiters; the order is NOT important
387 wdelim = url.find(c, start) # find first of this delim
388 if wdelim >= 0: # if found
389 delim = min(delim, wdelim) # use earliest delim position
390 return url[start:delim], url[delim:] # return (domain, rest)
391
392def urlsplit(url, scheme='', allow_fragments=True):
393 """Parse a URL into 5 components:
394 <scheme>://<netloc>/<path>?<query>#<fragment>
395 Return a 5-tuple: (scheme, netloc, path, query, fragment).
396 Note that we don't break the components up in smaller bits
397 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000398 url, scheme, _coerce_result = _coerce_args(url, scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000399 allow_fragments = bool(allow_fragments)
400 key = url, scheme, allow_fragments, type(url), type(scheme)
401 cached = _parse_cache.get(key, None)
402 if cached:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000403 return _coerce_result(cached)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000404 if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
405 clear_cache()
406 netloc = query = fragment = ''
407 i = url.find(':')
408 if i > 0:
409 if url[:i] == 'http': # optimize the common case
410 scheme = url[:i].lower()
411 url = url[i+1:]
412 if url[:2] == '//':
413 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000414 if (('[' in netloc and ']' not in netloc) or
415 (']' in netloc and '[' not in netloc)):
416 raise ValueError("Invalid IPv6 URL")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000417 if allow_fragments and '#' in url:
418 url, fragment = url.split('#', 1)
419 if '?' in url:
420 url, query = url.split('?', 1)
421 v = SplitResult(scheme, netloc, url, query, fragment)
422 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000423 return _coerce_result(v)
Senthil Kumaran397eb442011-04-15 18:20:24 +0800424 for c in url[:i]:
425 if c not in scheme_chars:
426 break
427 else:
Ezio Melotti6709b7d2012-05-19 17:15:19 +0300428 # make sure "url" is not actually a port number (in which case
429 # "scheme" is really part of the path)
430 rest = url[i+1:]
431 if not rest or any(c not in '0123456789' for c in rest):
432 # not a port number
433 scheme, url = url[:i].lower(), rest
Senthil Kumaran397eb442011-04-15 18:20:24 +0800434
Senthil Kumaran6be85c52010-02-19 07:42:50 +0000435 if url[:2] == '//':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000436 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000437 if (('[' in netloc and ']' not in netloc) or
438 (']' in netloc and '[' not in netloc)):
439 raise ValueError("Invalid IPv6 URL")
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800440 if allow_fragments and '#' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000441 url, fragment = url.split('#', 1)
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800442 if '?' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000443 url, query = url.split('?', 1)
444 v = SplitResult(scheme, netloc, url, query, fragment)
445 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000446 return _coerce_result(v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000447
448def urlunparse(components):
449 """Put a parsed URL back together again. This may result in a
450 slightly different, but equivalent URL, if the URL that was parsed
451 originally had redundant delimiters, e.g. a ? with an empty query
452 (the draft states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000453 scheme, netloc, url, params, query, fragment, _coerce_result = (
454 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000455 if params:
456 url = "%s;%s" % (url, params)
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000457 return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000458
459def urlunsplit(components):
Senthil Kumaran8749a632010-06-28 14:08:00 +0000460 """Combine the elements of a tuple as returned by urlsplit() into a
461 complete URL as a string. The data argument can be any five-item iterable.
462 This may result in a slightly different, but equivalent URL, if the URL that
463 was parsed originally had unnecessary delimiters (for example, a ? with an
464 empty query; the RFC states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000465 scheme, netloc, url, query, fragment, _coerce_result = (
466 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000467 if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
468 if url and url[:1] != '/': url = '/' + url
469 url = '//' + (netloc or '') + url
470 if scheme:
471 url = scheme + ':' + url
472 if query:
473 url = url + '?' + query
474 if fragment:
475 url = url + '#' + fragment
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000476 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000477
478def urljoin(base, url, allow_fragments=True):
479 """Join a base URL and a possibly relative URL to form an absolute
480 interpretation of the latter."""
481 if not base:
482 return url
483 if not url:
484 return base
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400485
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000486 base, url, _coerce_result = _coerce_args(base, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000487 bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
488 urlparse(base, '', allow_fragments)
489 scheme, netloc, path, params, query, fragment = \
490 urlparse(url, bscheme, allow_fragments)
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400491
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000492 if scheme != bscheme or scheme not in uses_relative:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000493 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000494 if scheme in uses_netloc:
495 if netloc:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000496 return _coerce_result(urlunparse((scheme, netloc, path,
497 params, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000498 netloc = bnetloc
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400499
Senthil Kumarandca5b862010-12-17 04:48:45 +0000500 if not path and not params:
Facundo Batista23e38562008-08-14 16:55:14 +0000501 path = bpath
Senthil Kumarandca5b862010-12-17 04:48:45 +0000502 params = bparams
Facundo Batista23e38562008-08-14 16:55:14 +0000503 if not query:
504 query = bquery
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000505 return _coerce_result(urlunparse((scheme, netloc, path,
506 params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400507
508 base_parts = bpath.split('/')
509 if base_parts[-1] != '':
510 # the last item is not a directory, so will not be taken into account
511 # in resolving the relative path
512 del base_parts[-1]
513
514 # for rfc3986, ignore all base path should the first character be root.
515 if path[:1] == '/':
516 segments = path.split('/')
517 else:
518 segments = base_parts + path.split('/')
Senthil Kumarana66e3882014-09-22 15:49:16 +0800519 # filter out elements that would cause redundant slashes on re-joining
520 # the resolved_path
Berker Peksag20416f72015-04-16 02:31:14 +0300521 segments[1:-1] = filter(None, segments[1:-1])
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400522
523 resolved_path = []
524
525 for seg in segments:
526 if seg == '..':
527 try:
528 resolved_path.pop()
529 except IndexError:
530 # ignore any .. segments that would otherwise cause an IndexError
531 # when popped from resolved_path if resolving for rfc3986
532 pass
533 elif seg == '.':
534 continue
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000535 else:
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400536 resolved_path.append(seg)
537
538 if segments[-1] in ('.', '..'):
539 # do some post-processing here. if the last segment was a relative dir,
540 # then we need to append the trailing '/'
541 resolved_path.append('')
542
543 return _coerce_result(urlunparse((scheme, netloc, '/'.join(
Senthil Kumarana66e3882014-09-22 15:49:16 +0800544 resolved_path) or '/', params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400545
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000546
547def urldefrag(url):
548 """Removes any existing fragment from URL.
549
550 Returns a tuple of the defragmented URL and the fragment. If
551 the URL contained no fragments, the second element is the
552 empty string.
553 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000554 url, _coerce_result = _coerce_args(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000555 if '#' in url:
556 s, n, p, a, q, frag = urlparse(url)
557 defrag = urlunparse((s, n, p, a, q, ''))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000558 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000559 frag = ''
560 defrag = url
561 return _coerce_result(DefragResult(defrag, frag))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000562
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200563_hexdig = '0123456789ABCDEFabcdef'
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100564_hextobyte = None
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200565
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000566def unquote_to_bytes(string):
567 """unquote_to_bytes('abc%20def') -> b'abc def'."""
568 # Note: strings are encoded as UTF-8. This is only an issue if it contains
569 # unescaped non-ASCII characters, which URIs should not.
Florent Xicluna82a3f8a2010-08-14 18:30:35 +0000570 if not string:
571 # Is it a string-like object?
572 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000573 return b''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000574 if isinstance(string, str):
575 string = string.encode('utf-8')
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200576 bits = string.split(b'%')
577 if len(bits) == 1:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000578 return string
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200579 res = [bits[0]]
580 append = res.append
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100581 # Delay the initialization of the table to not waste memory
582 # if the function is never called
583 global _hextobyte
584 if _hextobyte is None:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +0200585 _hextobyte = {(a + b).encode(): bytes.fromhex(a + b)
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100586 for a in _hexdig for b in _hexdig}
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200587 for item in bits[1:]:
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000588 try:
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200589 append(_hextobyte[item[:2]])
590 append(item[2:])
591 except KeyError:
592 append(b'%')
593 append(item)
594 return b''.join(res)
595
596_asciire = re.compile('([\x00-\x7f]+)')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000597
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000598def unquote(string, encoding='utf-8', errors='replace'):
599 """Replace %xx escapes by their single-character equivalent. The optional
600 encoding and errors parameters specify how to decode percent-encoded
601 sequences into Unicode characters, as accepted by the bytes.decode()
602 method.
603 By default, percent-encoded sequences are decoded with UTF-8, and invalid
604 sequences are replaced by a placeholder character.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000605
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000606 unquote('abc%20def') -> 'abc def'.
607 """
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200608 if '%' not in string:
609 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000610 return string
611 if encoding is None:
612 encoding = 'utf-8'
613 if errors is None:
614 errors = 'replace'
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200615 bits = _asciire.split(string)
616 res = [bits[0]]
617 append = res.append
618 for i in range(1, len(bits), 2):
619 append(unquote_to_bytes(bits[i]).decode(encoding, errors))
620 append(bits[i + 1])
621 return ''.join(res)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000622
Senthil Kumaran257b9802017-04-04 21:19:43 -0700623
Victor Stinnerac71c542011-01-14 12:52:12 +0000624def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
625 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000626 """Parse a query given as a string argument.
627
628 Arguments:
629
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000630 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000631
632 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000633 percent-encoded queries should be treated as blank strings.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000634 A true value indicates that blanks should be retained as
635 blank strings. The default false value indicates that
636 blank values are to be ignored and treated as if they were
637 not included.
638
639 strict_parsing: flag indicating what to do with parsing errors.
640 If false (the default), errors are silently ignored.
641 If true, errors raise a ValueError exception.
Victor Stinnerac71c542011-01-14 12:52:12 +0000642
643 encoding and errors: specify how to decode percent-encoded sequences
644 into Unicode characters, as accepted by the bytes.decode() method.
Senthil Kumaran257b9802017-04-04 21:19:43 -0700645
646 Returns a dictionary.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000647 """
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700648 parsed_result = {}
Victor Stinnerac71c542011-01-14 12:52:12 +0000649 pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
650 encoding=encoding, errors=errors)
651 for name, value in pairs:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700652 if name in parsed_result:
653 parsed_result[name].append(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000654 else:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700655 parsed_result[name] = [value]
656 return parsed_result
Facundo Batistac469d4c2008-09-03 22:49:01 +0000657
Senthil Kumaran257b9802017-04-04 21:19:43 -0700658
Victor Stinnerac71c542011-01-14 12:52:12 +0000659def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
660 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000661 """Parse a query given as a string argument.
662
Senthil Kumaran257b9802017-04-04 21:19:43 -0700663 Arguments:
Facundo Batistac469d4c2008-09-03 22:49:01 +0000664
Senthil Kumaran257b9802017-04-04 21:19:43 -0700665 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000666
Senthil Kumaran257b9802017-04-04 21:19:43 -0700667 keep_blank_values: flag indicating whether blank values in
668 percent-encoded queries should be treated as blank strings.
669 A true value indicates that blanks should be retained as blank
670 strings. The default false value indicates that blank values
671 are to be ignored and treated as if they were not included.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000672
Senthil Kumaran257b9802017-04-04 21:19:43 -0700673 strict_parsing: flag indicating what to do with parsing errors. If
674 false (the default), errors are silently ignored. If true,
675 errors raise a ValueError exception.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000676
Senthil Kumaran257b9802017-04-04 21:19:43 -0700677 encoding and errors: specify how to decode percent-encoded sequences
678 into Unicode characters, as accepted by the bytes.decode() method.
Victor Stinnerac71c542011-01-14 12:52:12 +0000679
Senthil Kumaran257b9802017-04-04 21:19:43 -0700680 Returns a list, as G-d intended.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000681 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000682 qs, _coerce_result = _coerce_args(qs)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000683 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
684 r = []
685 for name_value in pairs:
686 if not name_value and not strict_parsing:
687 continue
688 nv = name_value.split('=', 1)
689 if len(nv) != 2:
690 if strict_parsing:
691 raise ValueError("bad query field: %r" % (name_value,))
692 # Handle case of a control-name with no equal sign
693 if keep_blank_values:
694 nv.append('')
695 else:
696 continue
697 if len(nv[1]) or keep_blank_values:
Victor Stinnerac71c542011-01-14 12:52:12 +0000698 name = nv[0].replace('+', ' ')
699 name = unquote(name, encoding=encoding, errors=errors)
700 name = _coerce_result(name)
701 value = nv[1].replace('+', ' ')
702 value = unquote(value, encoding=encoding, errors=errors)
703 value = _coerce_result(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000704 r.append((name, value))
Facundo Batistac469d4c2008-09-03 22:49:01 +0000705 return r
706
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000707def unquote_plus(string, encoding='utf-8', errors='replace'):
708 """Like unquote(), but also replace plus signs by spaces, as required for
709 unquoting HTML form values.
710
711 unquote_plus('%7e/abc+def') -> '~/abc def'
712 """
713 string = string.replace('+', ' ')
714 return unquote(string, encoding, errors)
715
716_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
717 b'abcdefghijklmnopqrstuvwxyz'
718 b'0123456789'
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530719 b'_.-~')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000720_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
721_safe_quoters = {}
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000722
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000723class Quoter(collections.defaultdict):
724 """A mapping from bytes (in range(0,256)) to strings.
725
726 String values are percent-encoded byte values, unless the key < 128, and
727 in the "safe" set (either the specified safe set, or default set).
728 """
729 # Keeps a cache internally, using defaultdict, for efficiency (lookups
730 # of cached keys don't call Python code at all).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000731 def __init__(self, safe):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000732 """safe: bytes object."""
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000733 self.safe = _ALWAYS_SAFE.union(safe)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000734
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000735 def __repr__(self):
736 # Without this, will just display as a defaultdict
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300737 return "<%s %r>" % (self.__class__.__name__, dict(self))
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000738
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000739 def __missing__(self, b):
740 # Handle a cache miss. Store quoted string in cache and return.
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000741 res = chr(b) if b in self.safe else '%{:02X}'.format(b)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000742 self[b] = res
743 return res
744
745def quote(string, safe='/', encoding=None, errors=None):
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000746 """quote('abc def') -> 'abc%20def'
747
748 Each part of a URL, e.g. the path info, the query, etc., has a
749 different set of reserved characters that must be quoted.
750
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530751 RFC 3986 Uniform Resource Identifiers (URI): Generic Syntax lists
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000752 the following reserved characters.
753
754 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530755 "$" | "," | "~"
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000756
757 Each of these characters is reserved in some component of a URL,
758 but not necessarily in all of them.
759
Ratnadeep Debnath21024f02017-02-25 14:30:28 +0530760 Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
761 Now, "~" is included in the set of reserved characters.
762
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000763 By default, the quote function is intended for quoting the path
764 section of a URL. Thus, it will not encode '/'. This character
765 is reserved, but in typical usage the quote function is being
766 called on a path where the existing slash characters are used as
767 reserved characters.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000768
R David Murray8c4e1122014-12-24 21:23:18 -0500769 string and safe may be either str or bytes objects. encoding and errors
770 must not be specified if string is a bytes object.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000771
772 The optional encoding and errors parameters specify how to deal with
773 non-ASCII characters, as accepted by the str.encode method.
774 By default, encoding='utf-8' (characters are encoded with UTF-8), and
775 errors='strict' (unsupported characters raise a UnicodeEncodeError).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000776 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000777 if isinstance(string, str):
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000778 if not string:
779 return string
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000780 if encoding is None:
781 encoding = 'utf-8'
782 if errors is None:
783 errors = 'strict'
784 string = string.encode(encoding, errors)
785 else:
786 if encoding is not None:
787 raise TypeError("quote() doesn't support 'encoding' for bytes")
788 if errors is not None:
789 raise TypeError("quote() doesn't support 'errors' for bytes")
790 return quote_from_bytes(string, safe)
791
792def quote_plus(string, safe='', encoding=None, errors=None):
793 """Like quote(), but also replace ' ' with '+', as required for quoting
794 HTML form values. Plus signs in the original string are escaped unless
795 they are included in safe. It also does not have safe default to '/'.
796 """
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000797 # Check if ' ' in string, where string may either be a str or bytes. If
798 # there are no spaces, the regular quote will produce the right answer.
799 if ((isinstance(string, str) and ' ' not in string) or
800 (isinstance(string, bytes) and b' ' not in string)):
801 return quote(string, safe, encoding, errors)
802 if isinstance(safe, str):
803 space = ' '
804 else:
805 space = b' '
Georg Brandlfaf41492009-05-26 18:31:11 +0000806 string = quote(string, safe + space, encoding, errors)
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000807 return string.replace(' ', '+')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000808
809def quote_from_bytes(bs, safe='/'):
810 """Like quote(), but accepts a bytes object rather than a str, and does
811 not perform string-to-bytes encoding. It always returns an ASCII string.
Senthil Kumaranffa4b2c2012-05-26 09:53:32 +0800812 quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000813 """
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000814 if not isinstance(bs, (bytes, bytearray)):
815 raise TypeError("quote_from_bytes() expected bytes")
816 if not bs:
817 return ''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000818 if isinstance(safe, str):
819 # Normalize 'safe' by converting to bytes and removing non-ASCII chars
820 safe = safe.encode('ascii', 'ignore')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000821 else:
822 safe = bytes([c for c in safe if c < 128])
823 if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
824 return bs.decode()
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000825 try:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000826 quoter = _safe_quoters[safe]
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000827 except KeyError:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000828 _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
829 return ''.join([quoter(char) for char in bs])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000830
R David Murrayc17686f2015-05-17 20:44:50 -0400831def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
832 quote_via=quote_plus):
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700833 """Encode a dict or sequence of two-element tuples into a URL query string.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000834
835 If any values in the query arg are sequences and doseq is true, each
836 sequence element is converted to a separate parameter.
837
838 If the query arg is a sequence of two-element tuples, the order of the
839 parameters in the output will match the order of parameters in the
840 input.
Senthil Kumarandf022da2010-07-03 17:48:22 +0000841
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700842 The components of a query arg may each be either a string or a bytes type.
R David Murray8c4e1122014-12-24 21:23:18 -0500843
R David Murrayc17686f2015-05-17 20:44:50 -0400844 The safe, encoding, and errors parameters are passed down to the function
845 specified by quote_via (encoding and errors only if a component is a str).
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000846 """
847
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000848 if hasattr(query, "items"):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000849 query = query.items()
850 else:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000851 # It's a bother at times that strings and string-like objects are
852 # sequences.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000853 try:
854 # non-sequence items should not work with len()
855 # non-empty strings will fail this
856 if len(query) and not isinstance(query[0], tuple):
857 raise TypeError
Jeremy Hylton230feba2009-03-26 16:56:59 +0000858 # Zero-length sequences of all types will get here and succeed,
859 # but that's a minor nit. Since the original implementation
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000860 # allowed empty dicts that type of behavior probably should be
861 # preserved for consistency
862 except TypeError:
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000863 ty, va, tb = sys.exc_info()
864 raise TypeError("not a valid non-string sequence "
865 "or mapping object").with_traceback(tb)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000866
867 l = []
868 if not doseq:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000869 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000870 if isinstance(k, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400871 k = quote_via(k, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000872 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400873 k = quote_via(str(k), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000874
875 if isinstance(v, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400876 v = quote_via(v, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000877 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400878 v = quote_via(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000879 l.append(k + '=' + v)
880 else:
881 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000882 if isinstance(k, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400883 k = quote_via(k, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000884 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400885 k = quote_via(str(k), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000886
887 if isinstance(v, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400888 v = quote_via(v, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000889 l.append(k + '=' + v)
890 elif isinstance(v, str):
R David Murrayc17686f2015-05-17 20:44:50 -0400891 v = quote_via(v, safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000892 l.append(k + '=' + v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000893 else:
894 try:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000895 # Is this a sufficient test for sequence-ness?
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000896 x = len(v)
897 except TypeError:
898 # not a sequence
R David Murrayc17686f2015-05-17 20:44:50 -0400899 v = quote_via(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000900 l.append(k + '=' + v)
901 else:
902 # loop over the sequence
903 for elt in v:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000904 if isinstance(elt, bytes):
R David Murrayc17686f2015-05-17 20:44:50 -0400905 elt = quote_via(elt, safe)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000906 else:
R David Murrayc17686f2015-05-17 20:44:50 -0400907 elt = quote_via(str(elt), safe, encoding, errors)
Senthil Kumarandf022da2010-07-03 17:48:22 +0000908 l.append(k + '=' + elt)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000909 return '&'.join(l)
910
Georg Brandl13e89462008-07-01 19:56:00 +0000911def to_bytes(url):
912 """to_bytes(u"URL") --> 'URL'."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000913 # Most URL schemes require ASCII. If that changes, the conversion
914 # can be relaxed.
Georg Brandl13e89462008-07-01 19:56:00 +0000915 # XXX get rid of to_bytes()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000916 if isinstance(url, str):
917 try:
918 url = url.encode("ASCII").decode()
919 except UnicodeError:
920 raise UnicodeError("URL " + repr(url) +
921 " contains non-ASCII characters")
922 return url
923
924def unwrap(url):
925 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
926 url = str(url).strip()
927 if url[:1] == '<' and url[-1:] == '>':
928 url = url[1:-1].strip()
929 if url[:4] == 'URL:': url = url[4:].strip()
930 return url
931
932_typeprog = None
933def splittype(url):
934 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
935 global _typeprog
936 if _typeprog is None:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200937 _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000938
939 match = _typeprog.match(url)
940 if match:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200941 scheme, data = match.groups()
942 return scheme.lower(), data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000943 return None, url
944
945_hostprog = None
946def splithost(url):
947 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
948 global _hostprog
949 if _hostprog is None:
postmasters90e01e52017-06-20 06:02:44 -0700950 _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000951
952 match = _hostprog.match(url)
Senthil Kumaranc2958622010-11-22 04:48:26 +0000953 if match:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200954 host_port, path = match.groups()
955 if path and path[0] != '/':
Senthil Kumaranc2958622010-11-22 04:48:26 +0000956 path = '/' + path
957 return host_port, path
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000958 return None, url
959
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000960def splituser(host):
961 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200962 user, delim, host = host.rpartition('@')
963 return (user if delim else None), host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000964
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000965def splitpasswd(user):
966 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200967 user, delim, passwd = user.partition(':')
968 return user, (passwd if delim else None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000969
970# splittag('/path#tag') --> '/path', 'tag'
971_portprog = None
972def splitport(host):
973 """splitport('host:port') --> 'host', 'port'."""
974 global _portprog
975 if _portprog is None:
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200976 _portprog = re.compile('(.*):([0-9]*)$', re.DOTALL)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000977
978 match = _portprog.match(host)
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200979 if match:
980 host, port = match.groups()
981 if port:
982 return host, port
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000983 return host, None
984
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000985def splitnport(host, defport=-1):
986 """Split host and port, returning numeric port.
987 Return given default port if no ':' found; defaults to -1.
988 Return numerical port if a valid number are found after ':'.
989 Return None if ':' but not a valid number."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +0200990 host, delim, port = host.rpartition(':')
991 if not delim:
992 host = port
993 elif port:
994 try:
995 nport = int(port)
996 except ValueError:
997 nport = None
998 return host, nport
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000999 return host, defport
1000
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001001def splitquery(url):
1002 """splitquery('/path?query') --> '/path', 'query'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001003 path, delim, query = url.rpartition('?')
1004 if delim:
1005 return path, query
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001006 return url, None
1007
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001008def splittag(url):
1009 """splittag('/path#tag') --> '/path', 'tag'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001010 path, delim, tag = url.rpartition('#')
1011 if delim:
1012 return path, tag
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001013 return url, None
1014
1015def splitattr(url):
1016 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1017 '/path', ['attr1=value1', 'attr2=value2', ...]."""
1018 words = url.split(';')
1019 return words[0], words[1:]
1020
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001021def splitvalue(attr):
1022 """splitvalue('attr=value') --> 'attr', 'value'."""
Serhiy Storchaka44eceb62015-03-03 20:21:35 +02001023 attr, delim, value = attr.partition('=')
1024 return attr, (value if delim else None)