blob: 8bbeab62007b085c3d56cbd784ea38b753cc5c79 [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",
Guido van Rossum52dbbb92008-08-18 21:44:30 +000037 "unquote", "unquote_plus", "unquote_to_bytes"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +000038
39# A classification of schemes ('' means apply by default)
40uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'imap',
41 'wais', 'file', 'https', 'shttp', 'mms',
Senthil Kumaran2a157d22011-08-03 18:37:22 +080042 'prospero', 'rtsp', 'rtspu', '', 'sftp',
43 'svn', 'svn+ssh']
Jeremy Hylton1afc1692008-06-18 20:49:58 +000044uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet',
45 'imap', 'wais', 'file', 'mms', 'https', 'shttp',
46 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '',
Florent Xiclunac7b8e862010-05-17 17:33:07 +000047 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh']
Jeremy Hylton1afc1692008-06-18 20:49:58 +000048uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap',
49 'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
Senthil Kumaraned301992012-12-24 14:00:20 -080050 'mms', '', 'sftp', 'tel']
Jeremy Hylton1afc1692008-06-18 20:49:58 +000051
Georg Brandla61b09f2012-08-24 18:15:29 +020052# These are not actually used anymore, but should stay for backwards
53# compatibility. (They are undocumented, but have a public-looking name.)
54non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
55 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
56uses_query = ['http', 'wais', 'imap', 'https', 'shttp', 'mms',
57 'gopher', 'rtsp', 'rtspu', 'sip', 'sips', '']
58uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news',
59 'nntp', 'wais', 'https', 'shttp', 'snews',
60 'file', 'prospero', '']
61
Jeremy Hylton1afc1692008-06-18 20:49:58 +000062# Characters valid in scheme names
63scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
64 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
65 '0123456789'
66 '+-.')
67
Nick Coghlan9fc443c2010-11-30 15:48:08 +000068# XXX: Consider replacing with functools.lru_cache
Jeremy Hylton1afc1692008-06-18 20:49:58 +000069MAX_CACHE_SIZE = 20
70_parse_cache = {}
71
72def clear_cache():
Antoine Pitrou2df5fc72009-12-08 19:38:17 +000073 """Clear the parse cache and the quoters cache."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +000074 _parse_cache.clear()
Antoine Pitrou2df5fc72009-12-08 19:38:17 +000075 _safe_quoters.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000076
77
Nick Coghlan9fc443c2010-11-30 15:48:08 +000078# Helpers for bytes handling
79# For 3.2, we deliberately require applications that
80# handle improperly quoted URLs to do their own
81# decoding and encoding. If valid use cases are
82# presented, we may relax this by using latin-1
83# decoding internally for 3.3
84_implicit_encoding = 'ascii'
85_implicit_errors = 'strict'
86
87def _noop(obj):
88 return obj
89
90def _encode_result(obj, encoding=_implicit_encoding,
91 errors=_implicit_errors):
92 return obj.encode(encoding, errors)
93
94def _decode_args(args, encoding=_implicit_encoding,
95 errors=_implicit_errors):
96 return tuple(x.decode(encoding, errors) if x else '' for x in args)
97
98def _coerce_args(*args):
99 # Invokes decode if necessary to create str args
100 # and returns the coerced inputs along with
101 # an appropriate result coercion function
102 # - noop for str inputs
103 # - encoding function otherwise
104 str_input = isinstance(args[0], str)
105 for arg in args[1:]:
106 # We special-case the empty string to support the
107 # "scheme=''" default argument to some functions
108 if arg and isinstance(arg, str) != str_input:
109 raise TypeError("Cannot mix str and non-str arguments")
110 if str_input:
111 return args + (_noop,)
112 return _decode_args(args) + (_encode_result,)
113
114# Result objects are more helpful than simple tuples
115class _ResultMixinStr(object):
116 """Standard approach to encoding parsed results from str to bytes"""
117 __slots__ = ()
118
119 def encode(self, encoding='ascii', errors='strict'):
120 return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
121
122
123class _ResultMixinBytes(object):
124 """Standard approach to decoding parsed results from bytes to str"""
125 __slots__ = ()
126
127 def decode(self, encoding='ascii', errors='strict'):
128 return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
129
130
131class _NetlocResultMixinBase(object):
132 """Shared methods for the parsed result objects containing a netloc element"""
133 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000134
135 @property
136 def username(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000137 return self._userinfo[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000138
139 @property
140 def password(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000141 return self._userinfo[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000142
143 @property
144 def hostname(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000145 hostname = self._hostinfo[0]
146 if not hostname:
147 hostname = None
148 elif hostname is not None:
149 hostname = hostname.lower()
150 return hostname
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000151
152 @property
153 def port(self):
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000154 port = self._hostinfo[1]
155 if port is not None:
156 port = int(port, 10)
Senthil Kumaran2fc5a502012-05-24 21:56:17 +0800157 # Return None on an illegal port
158 if not ( 0 <= port <= 65535):
159 return None
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000160 return port
161
162
163class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
164 __slots__ = ()
165
166 @property
167 def _userinfo(self):
168 netloc = self.netloc
169 userinfo, have_info, hostinfo = netloc.rpartition('@')
170 if have_info:
171 username, have_password, password = userinfo.partition(':')
172 if not have_password:
173 password = None
Senthil Kumaranad02d232010-04-16 03:02:13 +0000174 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000175 username = password = None
176 return username, password
177
178 @property
179 def _hostinfo(self):
180 netloc = self.netloc
181 _, _, hostinfo = netloc.rpartition('@')
182 _, have_open_br, bracketed = hostinfo.partition('[')
183 if have_open_br:
184 hostname, _, port = bracketed.partition(']')
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200185 _, _, port = port.partition(':')
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000186 else:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200187 hostname, _, port = hostinfo.partition(':')
188 if not port:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000189 port = None
190 return hostname, port
191
192
193class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
194 __slots__ = ()
195
196 @property
197 def _userinfo(self):
198 netloc = self.netloc
199 userinfo, have_info, hostinfo = netloc.rpartition(b'@')
200 if have_info:
201 username, have_password, password = userinfo.partition(b':')
202 if not have_password:
203 password = None
204 else:
205 username = password = None
206 return username, password
207
208 @property
209 def _hostinfo(self):
210 netloc = self.netloc
211 _, _, hostinfo = netloc.rpartition(b'@')
212 _, have_open_br, bracketed = hostinfo.partition(b'[')
213 if have_open_br:
214 hostname, _, port = bracketed.partition(b']')
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200215 _, _, port = port.partition(b':')
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000216 else:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200217 hostname, _, port = hostinfo.partition(b':')
218 if not port:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000219 port = None
220 return hostname, port
221
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000222
223from collections import namedtuple
224
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000225_DefragResultBase = namedtuple('DefragResult', 'url fragment')
226_SplitResultBase = namedtuple('SplitResult', 'scheme netloc path query fragment')
227_ParseResultBase = namedtuple('ParseResult', 'scheme netloc path params query fragment')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000228
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000229# For backwards compatibility, alias _NetlocResultMixinStr
230# ResultBase is no longer part of the documented API, but it is
231# retained since deprecating it isn't worth the hassle
232ResultBase = _NetlocResultMixinStr
233
234# Structured result objects for string data
235class DefragResult(_DefragResultBase, _ResultMixinStr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000236 __slots__ = ()
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000237 def geturl(self):
238 if self.fragment:
239 return self.url + '#' + self.fragment
240 else:
241 return self.url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000242
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000243class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
244 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000245 def geturl(self):
246 return urlunsplit(self)
247
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000248class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000249 __slots__ = ()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000250 def geturl(self):
251 return urlunparse(self)
252
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000253# Structured result objects for bytes data
254class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
255 __slots__ = ()
256 def geturl(self):
257 if self.fragment:
258 return self.url + b'#' + self.fragment
259 else:
260 return self.url
261
262class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
263 __slots__ = ()
264 def geturl(self):
265 return urlunsplit(self)
266
267class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
268 __slots__ = ()
269 def geturl(self):
270 return urlunparse(self)
271
272# Set up the encode/decode result pairs
273def _fix_result_transcoding():
274 _result_pairs = (
275 (DefragResult, DefragResultBytes),
276 (SplitResult, SplitResultBytes),
277 (ParseResult, ParseResultBytes),
278 )
279 for _decoded, _encoded in _result_pairs:
280 _decoded._encoded_counterpart = _encoded
281 _encoded._decoded_counterpart = _decoded
282
283_fix_result_transcoding()
284del _fix_result_transcoding
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000285
286def urlparse(url, scheme='', allow_fragments=True):
287 """Parse a URL into 6 components:
288 <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
289 Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
290 Note that we don't break the components up in smaller bits
291 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000292 url, scheme, _coerce_result = _coerce_args(url, scheme)
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700293 splitresult = urlsplit(url, scheme, allow_fragments)
294 scheme, netloc, url, query, fragment = splitresult
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000295 if scheme in uses_params and ';' in url:
296 url, params = _splitparams(url)
297 else:
298 params = ''
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000299 result = ParseResult(scheme, netloc, url, params, query, fragment)
300 return _coerce_result(result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000301
302def _splitparams(url):
303 if '/' in url:
304 i = url.find(';', url.rfind('/'))
305 if i < 0:
306 return url, ''
307 else:
308 i = url.find(';')
309 return url[:i], url[i+1:]
310
311def _splitnetloc(url, start=0):
312 delim = len(url) # position of end of domain part of url, default is end
313 for c in '/?#': # look for delimiters; the order is NOT important
314 wdelim = url.find(c, start) # find first of this delim
315 if wdelim >= 0: # if found
316 delim = min(delim, wdelim) # use earliest delim position
317 return url[start:delim], url[delim:] # return (domain, rest)
318
319def urlsplit(url, scheme='', allow_fragments=True):
320 """Parse a URL into 5 components:
321 <scheme>://<netloc>/<path>?<query>#<fragment>
322 Return a 5-tuple: (scheme, netloc, path, query, fragment).
323 Note that we don't break the components up in smaller bits
324 (e.g. netloc is a single string) and we don't expand % escapes."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000325 url, scheme, _coerce_result = _coerce_args(url, scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000326 allow_fragments = bool(allow_fragments)
327 key = url, scheme, allow_fragments, type(url), type(scheme)
328 cached = _parse_cache.get(key, None)
329 if cached:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000330 return _coerce_result(cached)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000331 if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
332 clear_cache()
333 netloc = query = fragment = ''
334 i = url.find(':')
335 if i > 0:
336 if url[:i] == 'http': # optimize the common case
337 scheme = url[:i].lower()
338 url = url[i+1:]
339 if url[:2] == '//':
340 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000341 if (('[' in netloc and ']' not in netloc) or
342 (']' in netloc and '[' not in netloc)):
343 raise ValueError("Invalid IPv6 URL")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000344 if allow_fragments and '#' in url:
345 url, fragment = url.split('#', 1)
346 if '?' in url:
347 url, query = url.split('?', 1)
348 v = SplitResult(scheme, netloc, url, query, fragment)
349 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000350 return _coerce_result(v)
Senthil Kumaran397eb442011-04-15 18:20:24 +0800351 for c in url[:i]:
352 if c not in scheme_chars:
353 break
354 else:
Ezio Melotti6709b7d2012-05-19 17:15:19 +0300355 # make sure "url" is not actually a port number (in which case
356 # "scheme" is really part of the path)
357 rest = url[i+1:]
358 if not rest or any(c not in '0123456789' for c in rest):
359 # not a port number
360 scheme, url = url[:i].lower(), rest
Senthil Kumaran397eb442011-04-15 18:20:24 +0800361
Senthil Kumaran6be85c52010-02-19 07:42:50 +0000362 if url[:2] == '//':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000363 netloc, url = _splitnetloc(url, 2)
Senthil Kumaran7a1e09f2010-04-22 12:19:46 +0000364 if (('[' in netloc and ']' not in netloc) or
365 (']' in netloc and '[' not in netloc)):
366 raise ValueError("Invalid IPv6 URL")
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800367 if allow_fragments and '#' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000368 url, fragment = url.split('#', 1)
Senthil Kumaran1be320e2012-05-19 08:12:00 +0800369 if '?' in url:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000370 url, query = url.split('?', 1)
371 v = SplitResult(scheme, netloc, url, query, fragment)
372 _parse_cache[key] = v
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000373 return _coerce_result(v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000374
375def urlunparse(components):
376 """Put a parsed URL back together again. This may result in a
377 slightly different, but equivalent URL, if the URL that was parsed
378 originally had redundant delimiters, e.g. a ? with an empty query
379 (the draft states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000380 scheme, netloc, url, params, query, fragment, _coerce_result = (
381 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000382 if params:
383 url = "%s;%s" % (url, params)
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000384 return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000385
386def urlunsplit(components):
Senthil Kumaran8749a632010-06-28 14:08:00 +0000387 """Combine the elements of a tuple as returned by urlsplit() into a
388 complete URL as a string. The data argument can be any five-item iterable.
389 This may result in a slightly different, but equivalent URL, if the URL that
390 was parsed originally had unnecessary delimiters (for example, a ? with an
391 empty query; the RFC states that these are equivalent)."""
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000392 scheme, netloc, url, query, fragment, _coerce_result = (
393 _coerce_args(*components))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000394 if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
395 if url and url[:1] != '/': url = '/' + url
396 url = '//' + (netloc or '') + url
397 if scheme:
398 url = scheme + ':' + url
399 if query:
400 url = url + '?' + query
401 if fragment:
402 url = url + '#' + fragment
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000403 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000404
405def urljoin(base, url, allow_fragments=True):
406 """Join a base URL and a possibly relative URL to form an absolute
407 interpretation of the latter."""
408 if not base:
409 return url
410 if not url:
411 return base
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400412
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000413 base, url, _coerce_result = _coerce_args(base, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000414 bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
415 urlparse(base, '', allow_fragments)
416 scheme, netloc, path, params, query, fragment = \
417 urlparse(url, bscheme, allow_fragments)
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400418
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000419 if scheme != bscheme or scheme not in uses_relative:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000420 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000421 if scheme in uses_netloc:
422 if netloc:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000423 return _coerce_result(urlunparse((scheme, netloc, path,
424 params, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000425 netloc = bnetloc
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400426
Senthil Kumarandca5b862010-12-17 04:48:45 +0000427 if not path and not params:
Facundo Batista23e38562008-08-14 16:55:14 +0000428 path = bpath
Senthil Kumarandca5b862010-12-17 04:48:45 +0000429 params = bparams
Facundo Batista23e38562008-08-14 16:55:14 +0000430 if not query:
431 query = bquery
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000432 return _coerce_result(urlunparse((scheme, netloc, path,
433 params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400434
435 base_parts = bpath.split('/')
436 if base_parts[-1] != '':
437 # the last item is not a directory, so will not be taken into account
438 # in resolving the relative path
439 del base_parts[-1]
440
441 # for rfc3986, ignore all base path should the first character be root.
442 if path[:1] == '/':
443 segments = path.split('/')
444 else:
445 segments = base_parts + path.split('/')
Senthil Kumarana66e3882014-09-22 15:49:16 +0800446 # filter out elements that would cause redundant slashes on re-joining
447 # the resolved_path
448 segments = segments[0:1] + [
449 s for s in segments[1:-1] if len(s) > 0] + segments[-1:]
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400450
451 resolved_path = []
452
453 for seg in segments:
454 if seg == '..':
455 try:
456 resolved_path.pop()
457 except IndexError:
458 # ignore any .. segments that would otherwise cause an IndexError
459 # when popped from resolved_path if resolving for rfc3986
460 pass
461 elif seg == '.':
462 continue
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000463 else:
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400464 resolved_path.append(seg)
465
466 if segments[-1] in ('.', '..'):
467 # do some post-processing here. if the last segment was a relative dir,
468 # then we need to append the trailing '/'
469 resolved_path.append('')
470
471 return _coerce_result(urlunparse((scheme, netloc, '/'.join(
Senthil Kumarana66e3882014-09-22 15:49:16 +0800472 resolved_path) or '/', params, query, fragment)))
Antoine Pitrou55ac5b32014-08-21 19:16:17 -0400473
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000474
475def urldefrag(url):
476 """Removes any existing fragment from URL.
477
478 Returns a tuple of the defragmented URL and the fragment. If
479 the URL contained no fragments, the second element is the
480 empty string.
481 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000482 url, _coerce_result = _coerce_args(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000483 if '#' in url:
484 s, n, p, a, q, frag = urlparse(url)
485 defrag = urlunparse((s, n, p, a, q, ''))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000486 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000487 frag = ''
488 defrag = url
489 return _coerce_result(DefragResult(defrag, frag))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000490
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200491_hexdig = '0123456789ABCDEFabcdef'
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100492_hextobyte = None
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200493
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000494def unquote_to_bytes(string):
495 """unquote_to_bytes('abc%20def') -> b'abc def'."""
496 # Note: strings are encoded as UTF-8. This is only an issue if it contains
497 # unescaped non-ASCII characters, which URIs should not.
Florent Xicluna82a3f8a2010-08-14 18:30:35 +0000498 if not string:
499 # Is it a string-like object?
500 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000501 return b''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000502 if isinstance(string, str):
503 string = string.encode('utf-8')
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200504 bits = string.split(b'%')
505 if len(bits) == 1:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000506 return string
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200507 res = [bits[0]]
508 append = res.append
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100509 # Delay the initialization of the table to not waste memory
510 # if the function is never called
511 global _hextobyte
512 if _hextobyte is None:
513 _hextobyte = {(a + b).encode(): bytes([int(a + b, 16)])
514 for a in _hexdig for b in _hexdig}
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200515 for item in bits[1:]:
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000516 try:
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200517 append(_hextobyte[item[:2]])
518 append(item[2:])
519 except KeyError:
520 append(b'%')
521 append(item)
522 return b''.join(res)
523
524_asciire = re.compile('([\x00-\x7f]+)')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000525
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000526def unquote(string, encoding='utf-8', errors='replace'):
527 """Replace %xx escapes by their single-character equivalent. The optional
528 encoding and errors parameters specify how to decode percent-encoded
529 sequences into Unicode characters, as accepted by the bytes.decode()
530 method.
531 By default, percent-encoded sequences are decoded with UTF-8, and invalid
532 sequences are replaced by a placeholder character.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000533
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000534 unquote('abc%20def') -> 'abc def'.
535 """
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200536 if '%' not in string:
537 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000538 return string
539 if encoding is None:
540 encoding = 'utf-8'
541 if errors is None:
542 errors = 'replace'
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200543 bits = _asciire.split(string)
544 res = [bits[0]]
545 append = res.append
546 for i in range(1, len(bits), 2):
547 append(unquote_to_bytes(bits[i]).decode(encoding, errors))
548 append(bits[i + 1])
549 return ''.join(res)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000550
Victor Stinnerac71c542011-01-14 12:52:12 +0000551def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
552 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000553 """Parse a query given as a string argument.
554
555 Arguments:
556
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000557 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000558
559 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000560 percent-encoded queries should be treated as blank strings.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000561 A true value indicates that blanks should be retained as
562 blank strings. The default false value indicates that
563 blank values are to be ignored and treated as if they were
564 not included.
565
566 strict_parsing: flag indicating what to do with parsing errors.
567 If false (the default), errors are silently ignored.
568 If true, errors raise a ValueError exception.
Victor Stinnerac71c542011-01-14 12:52:12 +0000569
570 encoding and errors: specify how to decode percent-encoded sequences
571 into Unicode characters, as accepted by the bytes.decode() method.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000572 """
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700573 parsed_result = {}
Victor Stinnerac71c542011-01-14 12:52:12 +0000574 pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
575 encoding=encoding, errors=errors)
576 for name, value in pairs:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700577 if name in parsed_result:
578 parsed_result[name].append(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000579 else:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700580 parsed_result[name] = [value]
581 return parsed_result
Facundo Batistac469d4c2008-09-03 22:49:01 +0000582
Victor Stinnerac71c542011-01-14 12:52:12 +0000583def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
584 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000585 """Parse a query given as a string argument.
586
587 Arguments:
588
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000589 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000590
591 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000592 percent-encoded queries should be treated as blank strings. A
Facundo Batistac469d4c2008-09-03 22:49:01 +0000593 true value indicates that blanks should be retained as blank
594 strings. The default false value indicates that blank values
595 are to be ignored and treated as if they were not included.
596
597 strict_parsing: flag indicating what to do with parsing errors. If
598 false (the default), errors are silently ignored. If true,
599 errors raise a ValueError exception.
600
Victor Stinnerac71c542011-01-14 12:52:12 +0000601 encoding and errors: specify how to decode percent-encoded sequences
602 into Unicode characters, as accepted by the bytes.decode() method.
603
Facundo Batistac469d4c2008-09-03 22:49:01 +0000604 Returns a list, as G-d intended.
605 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000606 qs, _coerce_result = _coerce_args(qs)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000607 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
608 r = []
609 for name_value in pairs:
610 if not name_value and not strict_parsing:
611 continue
612 nv = name_value.split('=', 1)
613 if len(nv) != 2:
614 if strict_parsing:
615 raise ValueError("bad query field: %r" % (name_value,))
616 # Handle case of a control-name with no equal sign
617 if keep_blank_values:
618 nv.append('')
619 else:
620 continue
621 if len(nv[1]) or keep_blank_values:
Victor Stinnerac71c542011-01-14 12:52:12 +0000622 name = nv[0].replace('+', ' ')
623 name = unquote(name, encoding=encoding, errors=errors)
624 name = _coerce_result(name)
625 value = nv[1].replace('+', ' ')
626 value = unquote(value, encoding=encoding, errors=errors)
627 value = _coerce_result(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000628 r.append((name, value))
Facundo Batistac469d4c2008-09-03 22:49:01 +0000629 return r
630
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000631def unquote_plus(string, encoding='utf-8', errors='replace'):
632 """Like unquote(), but also replace plus signs by spaces, as required for
633 unquoting HTML form values.
634
635 unquote_plus('%7e/abc+def') -> '~/abc def'
636 """
637 string = string.replace('+', ' ')
638 return unquote(string, encoding, errors)
639
640_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
641 b'abcdefghijklmnopqrstuvwxyz'
642 b'0123456789'
643 b'_.-')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000644_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
645_safe_quoters = {}
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000646
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000647class Quoter(collections.defaultdict):
648 """A mapping from bytes (in range(0,256)) to strings.
649
650 String values are percent-encoded byte values, unless the key < 128, and
651 in the "safe" set (either the specified safe set, or default set).
652 """
653 # Keeps a cache internally, using defaultdict, for efficiency (lookups
654 # of cached keys don't call Python code at all).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000655 def __init__(self, safe):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000656 """safe: bytes object."""
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000657 self.safe = _ALWAYS_SAFE.union(safe)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000658
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000659 def __repr__(self):
660 # Without this, will just display as a defaultdict
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300661 return "<%s %r>" % (self.__class__.__name__, dict(self))
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000662
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000663 def __missing__(self, b):
664 # Handle a cache miss. Store quoted string in cache and return.
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000665 res = chr(b) if b in self.safe else '%{:02X}'.format(b)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000666 self[b] = res
667 return res
668
669def quote(string, safe='/', encoding=None, errors=None):
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000670 """quote('abc def') -> 'abc%20def'
671
672 Each part of a URL, e.g. the path info, the query, etc., has a
673 different set of reserved characters that must be quoted.
674
675 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
676 the following reserved characters.
677
678 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
679 "$" | ","
680
681 Each of these characters is reserved in some component of a URL,
682 but not necessarily in all of them.
683
684 By default, the quote function is intended for quoting the path
685 section of a URL. Thus, it will not encode '/'. This character
686 is reserved, but in typical usage the quote function is being
687 called on a path where the existing slash characters are used as
688 reserved characters.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000689
690 string and safe may be either str or bytes objects. encoding must
691 not be specified if string is a str.
692
693 The optional encoding and errors parameters specify how to deal with
694 non-ASCII characters, as accepted by the str.encode method.
695 By default, encoding='utf-8' (characters are encoded with UTF-8), and
696 errors='strict' (unsupported characters raise a UnicodeEncodeError).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000697 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000698 if isinstance(string, str):
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000699 if not string:
700 return string
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000701 if encoding is None:
702 encoding = 'utf-8'
703 if errors is None:
704 errors = 'strict'
705 string = string.encode(encoding, errors)
706 else:
707 if encoding is not None:
708 raise TypeError("quote() doesn't support 'encoding' for bytes")
709 if errors is not None:
710 raise TypeError("quote() doesn't support 'errors' for bytes")
711 return quote_from_bytes(string, safe)
712
713def quote_plus(string, safe='', encoding=None, errors=None):
714 """Like quote(), but also replace ' ' with '+', as required for quoting
715 HTML form values. Plus signs in the original string are escaped unless
716 they are included in safe. It also does not have safe default to '/'.
717 """
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000718 # Check if ' ' in string, where string may either be a str or bytes. If
719 # there are no spaces, the regular quote will produce the right answer.
720 if ((isinstance(string, str) and ' ' not in string) or
721 (isinstance(string, bytes) and b' ' not in string)):
722 return quote(string, safe, encoding, errors)
723 if isinstance(safe, str):
724 space = ' '
725 else:
726 space = b' '
Georg Brandlfaf41492009-05-26 18:31:11 +0000727 string = quote(string, safe + space, encoding, errors)
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000728 return string.replace(' ', '+')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000729
730def quote_from_bytes(bs, safe='/'):
731 """Like quote(), but accepts a bytes object rather than a str, and does
732 not perform string-to-bytes encoding. It always returns an ASCII string.
Senthil Kumaranffa4b2c2012-05-26 09:53:32 +0800733 quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000734 """
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000735 if not isinstance(bs, (bytes, bytearray)):
736 raise TypeError("quote_from_bytes() expected bytes")
737 if not bs:
738 return ''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000739 if isinstance(safe, str):
740 # Normalize 'safe' by converting to bytes and removing non-ASCII chars
741 safe = safe.encode('ascii', 'ignore')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000742 else:
743 safe = bytes([c for c in safe if c < 128])
744 if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
745 return bs.decode()
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000746 try:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000747 quoter = _safe_quoters[safe]
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000748 except KeyError:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000749 _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
750 return ''.join([quoter(char) for char in bs])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000751
Senthil Kumarandf022da2010-07-03 17:48:22 +0000752def urlencode(query, doseq=False, safe='', encoding=None, errors=None):
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700753 """Encode a dict or sequence of two-element tuples into a URL query string.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000754
755 If any values in the query arg are sequences and doseq is true, each
756 sequence element is converted to a separate parameter.
757
758 If the query arg is a sequence of two-element tuples, the order of the
759 parameters in the output will match the order of parameters in the
760 input.
Senthil Kumarandf022da2010-07-03 17:48:22 +0000761
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700762 The components of a query arg may each be either a string or a bytes type.
763 When a component is a string, the safe, encoding and error parameters are
764 sent to the quote_plus function for encoding.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000765 """
766
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000767 if hasattr(query, "items"):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000768 query = query.items()
769 else:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000770 # It's a bother at times that strings and string-like objects are
771 # sequences.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000772 try:
773 # non-sequence items should not work with len()
774 # non-empty strings will fail this
775 if len(query) and not isinstance(query[0], tuple):
776 raise TypeError
Jeremy Hylton230feba2009-03-26 16:56:59 +0000777 # Zero-length sequences of all types will get here and succeed,
778 # but that's a minor nit. Since the original implementation
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000779 # allowed empty dicts that type of behavior probably should be
780 # preserved for consistency
781 except TypeError:
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000782 ty, va, tb = sys.exc_info()
783 raise TypeError("not a valid non-string sequence "
784 "or mapping object").with_traceback(tb)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000785
786 l = []
787 if not doseq:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000788 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000789 if isinstance(k, bytes):
790 k = quote_plus(k, safe)
791 else:
792 k = quote_plus(str(k), safe, encoding, errors)
793
794 if isinstance(v, bytes):
795 v = quote_plus(v, safe)
796 else:
797 v = quote_plus(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000798 l.append(k + '=' + v)
799 else:
800 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000801 if isinstance(k, bytes):
802 k = quote_plus(k, safe)
803 else:
804 k = quote_plus(str(k), safe, encoding, errors)
805
806 if isinstance(v, bytes):
807 v = quote_plus(v, safe)
808 l.append(k + '=' + v)
809 elif isinstance(v, str):
810 v = quote_plus(v, safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000811 l.append(k + '=' + v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000812 else:
813 try:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000814 # Is this a sufficient test for sequence-ness?
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000815 x = len(v)
816 except TypeError:
817 # not a sequence
Senthil Kumarandf022da2010-07-03 17:48:22 +0000818 v = quote_plus(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000819 l.append(k + '=' + v)
820 else:
821 # loop over the sequence
822 for elt in v:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000823 if isinstance(elt, bytes):
824 elt = quote_plus(elt, safe)
825 else:
826 elt = quote_plus(str(elt), safe, encoding, errors)
827 l.append(k + '=' + elt)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000828 return '&'.join(l)
829
830# Utilities to parse URLs (most of these return None for missing parts):
831# unwrap('<URL:type://host/path>') --> 'type://host/path'
832# splittype('type:opaquestring') --> 'type', 'opaquestring'
833# splithost('//host[:port]/path') --> 'host[:port]', '/path'
834# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
835# splitpasswd('user:passwd') -> 'user', 'passwd'
836# splitport('host:port') --> 'host', 'port'
837# splitquery('/path?query') --> '/path', 'query'
838# splittag('/path#tag') --> '/path', 'tag'
839# splitattr('/path;attr1=value1;attr2=value2;...') ->
840# '/path', ['attr1=value1', 'attr2=value2', ...]
841# splitvalue('attr=value') --> 'attr', 'value'
842# urllib.parse.unquote('abc%20def') -> 'abc def'
843# quote('abc def') -> 'abc%20def')
844
Georg Brandl13e89462008-07-01 19:56:00 +0000845def to_bytes(url):
846 """to_bytes(u"URL") --> 'URL'."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000847 # Most URL schemes require ASCII. If that changes, the conversion
848 # can be relaxed.
Georg Brandl13e89462008-07-01 19:56:00 +0000849 # XXX get rid of to_bytes()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000850 if isinstance(url, str):
851 try:
852 url = url.encode("ASCII").decode()
853 except UnicodeError:
854 raise UnicodeError("URL " + repr(url) +
855 " contains non-ASCII characters")
856 return url
857
858def unwrap(url):
859 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
860 url = str(url).strip()
861 if url[:1] == '<' and url[-1:] == '>':
862 url = url[1:-1].strip()
863 if url[:4] == 'URL:': url = url[4:].strip()
864 return url
865
866_typeprog = None
867def splittype(url):
868 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
869 global _typeprog
870 if _typeprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000871 _typeprog = re.compile('^([^/:]+):')
872
873 match = _typeprog.match(url)
874 if match:
875 scheme = match.group(1)
876 return scheme.lower(), url[len(scheme) + 1:]
877 return None, url
878
879_hostprog = None
880def splithost(url):
881 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
882 global _hostprog
883 if _hostprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000884 _hostprog = re.compile('^//([^/?]*)(.*)$')
885
886 match = _hostprog.match(url)
Senthil Kumaranc2958622010-11-22 04:48:26 +0000887 if match:
888 host_port = match.group(1)
889 path = match.group(2)
890 if path and not path.startswith('/'):
891 path = '/' + path
892 return host_port, path
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000893 return None, url
894
895_userprog = None
896def splituser(host):
897 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
898 global _userprog
899 if _userprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000900 _userprog = re.compile('^(.*)@(.*)$')
901
902 match = _userprog.match(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000903 if match: return match.group(1, 2)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000904 return None, host
905
906_passwdprog = None
907def splitpasswd(user):
908 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
909 global _passwdprog
910 if _passwdprog is None:
Senthil Kumaraneaaec272009-03-30 21:54:41 +0000911 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000912
913 match = _passwdprog.match(user)
914 if match: return match.group(1, 2)
915 return user, None
916
917# splittag('/path#tag') --> '/path', 'tag'
918_portprog = None
919def splitport(host):
920 """splitport('host:port') --> 'host', 'port'."""
921 global _portprog
922 if _portprog is None:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200923 _portprog = re.compile('^(.*):([0-9]*)$')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000924
925 match = _portprog.match(host)
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200926 if match:
927 host, port = match.groups()
928 if port:
929 return host, port
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000930 return host, None
931
932_nportprog = None
933def splitnport(host, defport=-1):
934 """Split host and port, returning numeric port.
935 Return given default port if no ':' found; defaults to -1.
936 Return numerical port if a valid number are found after ':'.
937 Return None if ':' but not a valid number."""
938 global _nportprog
939 if _nportprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000940 _nportprog = re.compile('^(.*):(.*)$')
941
942 match = _nportprog.match(host)
943 if match:
944 host, port = match.group(1, 2)
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200945 if port:
946 try:
947 nport = int(port)
948 except ValueError:
949 nport = None
950 return host, nport
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000951 return host, defport
952
953_queryprog = None
954def splitquery(url):
955 """splitquery('/path?query') --> '/path', 'query'."""
956 global _queryprog
957 if _queryprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000958 _queryprog = re.compile('^(.*)\?([^?]*)$')
959
960 match = _queryprog.match(url)
961 if match: return match.group(1, 2)
962 return url, None
963
964_tagprog = None
965def splittag(url):
966 """splittag('/path#tag') --> '/path', 'tag'."""
967 global _tagprog
968 if _tagprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000969 _tagprog = re.compile('^(.*)#([^#]*)$')
970
971 match = _tagprog.match(url)
972 if match: return match.group(1, 2)
973 return url, None
974
975def splitattr(url):
976 """splitattr('/path;attr1=value1;attr2=value2;...') ->
977 '/path', ['attr1=value1', 'attr2=value2', ...]."""
978 words = url.split(';')
979 return words[0], words[1:]
980
981_valueprog = None
982def splitvalue(attr):
983 """splitvalue('attr=value') --> 'attr', 'value'."""
984 global _valueprog
985 if _valueprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000986 _valueprog = re.compile('^([^=]*)=(.*)$')
987
988 match = _valueprog.match(attr)
989 if match: return match.group(1, 2)
990 return attr, None