blob: a2a912d2abced1ce601a5b7c7c91747fbe340394 [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
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000412 base, url, _coerce_result = _coerce_args(base, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000413 bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
414 urlparse(base, '', allow_fragments)
415 scheme, netloc, path, params, query, fragment = \
416 urlparse(url, bscheme, allow_fragments)
417 if scheme != bscheme or scheme not in uses_relative:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000418 return _coerce_result(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000419 if scheme in uses_netloc:
420 if netloc:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000421 return _coerce_result(urlunparse((scheme, netloc, path,
422 params, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000423 netloc = bnetloc
424 if path[:1] == '/':
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000425 return _coerce_result(urlunparse((scheme, netloc, path,
426 params, query, fragment)))
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)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000434 segments = bpath.split('/')[:-1] + path.split('/')
435 # XXX The stuff below is bogus in various ways...
436 if segments[-1] == '.':
437 segments[-1] = ''
438 while '.' in segments:
439 segments.remove('.')
440 while 1:
441 i = 1
442 n = len(segments) - 1
443 while i < n:
444 if (segments[i] == '..'
445 and segments[i-1] not in ('', '..')):
446 del segments[i-1:i+1]
447 break
448 i = i+1
449 else:
450 break
451 if segments == ['', '..']:
452 segments[-1] = ''
453 elif len(segments) >= 2 and segments[-1] == '..':
454 segments[-2:] = ['']
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000455 return _coerce_result(urlunparse((scheme, netloc, '/'.join(segments),
456 params, query, fragment)))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000457
458def urldefrag(url):
459 """Removes any existing fragment from URL.
460
461 Returns a tuple of the defragmented URL and the fragment. If
462 the URL contained no fragments, the second element is the
463 empty string.
464 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000465 url, _coerce_result = _coerce_args(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000466 if '#' in url:
467 s, n, p, a, q, frag = urlparse(url)
468 defrag = urlunparse((s, n, p, a, q, ''))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000469 else:
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000470 frag = ''
471 defrag = url
472 return _coerce_result(DefragResult(defrag, frag))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000473
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200474_hexdig = '0123456789ABCDEFabcdef'
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100475_hextobyte = None
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200476
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000477def unquote_to_bytes(string):
478 """unquote_to_bytes('abc%20def') -> b'abc def'."""
479 # Note: strings are encoded as UTF-8. This is only an issue if it contains
480 # unescaped non-ASCII characters, which URIs should not.
Florent Xicluna82a3f8a2010-08-14 18:30:35 +0000481 if not string:
482 # Is it a string-like object?
483 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000484 return b''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000485 if isinstance(string, str):
486 string = string.encode('utf-8')
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200487 bits = string.split(b'%')
488 if len(bits) == 1:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000489 return string
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200490 res = [bits[0]]
491 append = res.append
Victor Stinnerd6a91a72014-03-17 22:38:41 +0100492 # Delay the initialization of the table to not waste memory
493 # if the function is never called
494 global _hextobyte
495 if _hextobyte is None:
496 _hextobyte = {(a + b).encode(): bytes([int(a + b, 16)])
497 for a in _hexdig for b in _hexdig}
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200498 for item in bits[1:]:
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000499 try:
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200500 append(_hextobyte[item[:2]])
501 append(item[2:])
502 except KeyError:
503 append(b'%')
504 append(item)
505 return b''.join(res)
506
507_asciire = re.compile('([\x00-\x7f]+)')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000508
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000509def unquote(string, encoding='utf-8', errors='replace'):
510 """Replace %xx escapes by their single-character equivalent. The optional
511 encoding and errors parameters specify how to decode percent-encoded
512 sequences into Unicode characters, as accepted by the bytes.decode()
513 method.
514 By default, percent-encoded sequences are decoded with UTF-8, and invalid
515 sequences are replaced by a placeholder character.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000516
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000517 unquote('abc%20def') -> 'abc def'.
518 """
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200519 if '%' not in string:
520 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000521 return string
522 if encoding is None:
523 encoding = 'utf-8'
524 if errors is None:
525 errors = 'replace'
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200526 bits = _asciire.split(string)
527 res = [bits[0]]
528 append = res.append
529 for i in range(1, len(bits), 2):
530 append(unquote_to_bytes(bits[i]).decode(encoding, errors))
531 append(bits[i + 1])
532 return ''.join(res)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000533
Victor Stinnerac71c542011-01-14 12:52:12 +0000534def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
535 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000536 """Parse a query given as a string argument.
537
538 Arguments:
539
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000540 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000541
542 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000543 percent-encoded queries should be treated as blank strings.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000544 A true value indicates that blanks should be retained as
545 blank strings. The default false value indicates that
546 blank values are to be ignored and treated as if they were
547 not included.
548
549 strict_parsing: flag indicating what to do with parsing errors.
550 If false (the default), errors are silently ignored.
551 If true, errors raise a ValueError exception.
Victor Stinnerac71c542011-01-14 12:52:12 +0000552
553 encoding and errors: specify how to decode percent-encoded sequences
554 into Unicode characters, as accepted by the bytes.decode() method.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000555 """
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700556 parsed_result = {}
Victor Stinnerac71c542011-01-14 12:52:12 +0000557 pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
558 encoding=encoding, errors=errors)
559 for name, value in pairs:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700560 if name in parsed_result:
561 parsed_result[name].append(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000562 else:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700563 parsed_result[name] = [value]
564 return parsed_result
Facundo Batistac469d4c2008-09-03 22:49:01 +0000565
Victor Stinnerac71c542011-01-14 12:52:12 +0000566def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
567 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000568 """Parse a query given as a string argument.
569
570 Arguments:
571
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000572 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000573
574 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000575 percent-encoded queries should be treated as blank strings. A
Facundo Batistac469d4c2008-09-03 22:49:01 +0000576 true value indicates that blanks should be retained as blank
577 strings. The default false value indicates that blank values
578 are to be ignored and treated as if they were not included.
579
580 strict_parsing: flag indicating what to do with parsing errors. If
581 false (the default), errors are silently ignored. If true,
582 errors raise a ValueError exception.
583
Victor Stinnerac71c542011-01-14 12:52:12 +0000584 encoding and errors: specify how to decode percent-encoded sequences
585 into Unicode characters, as accepted by the bytes.decode() method.
586
Facundo Batistac469d4c2008-09-03 22:49:01 +0000587 Returns a list, as G-d intended.
588 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000589 qs, _coerce_result = _coerce_args(qs)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000590 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
591 r = []
592 for name_value in pairs:
593 if not name_value and not strict_parsing:
594 continue
595 nv = name_value.split('=', 1)
596 if len(nv) != 2:
597 if strict_parsing:
598 raise ValueError("bad query field: %r" % (name_value,))
599 # Handle case of a control-name with no equal sign
600 if keep_blank_values:
601 nv.append('')
602 else:
603 continue
604 if len(nv[1]) or keep_blank_values:
Victor Stinnerac71c542011-01-14 12:52:12 +0000605 name = nv[0].replace('+', ' ')
606 name = unquote(name, encoding=encoding, errors=errors)
607 name = _coerce_result(name)
608 value = nv[1].replace('+', ' ')
609 value = unquote(value, encoding=encoding, errors=errors)
610 value = _coerce_result(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000611 r.append((name, value))
Facundo Batistac469d4c2008-09-03 22:49:01 +0000612 return r
613
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000614def unquote_plus(string, encoding='utf-8', errors='replace'):
615 """Like unquote(), but also replace plus signs by spaces, as required for
616 unquoting HTML form values.
617
618 unquote_plus('%7e/abc+def') -> '~/abc def'
619 """
620 string = string.replace('+', ' ')
621 return unquote(string, encoding, errors)
622
623_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
624 b'abcdefghijklmnopqrstuvwxyz'
625 b'0123456789'
626 b'_.-')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000627_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
628_safe_quoters = {}
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000629
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000630class Quoter(collections.defaultdict):
631 """A mapping from bytes (in range(0,256)) to strings.
632
633 String values are percent-encoded byte values, unless the key < 128, and
634 in the "safe" set (either the specified safe set, or default set).
635 """
636 # Keeps a cache internally, using defaultdict, for efficiency (lookups
637 # of cached keys don't call Python code at all).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000638 def __init__(self, safe):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000639 """safe: bytes object."""
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000640 self.safe = _ALWAYS_SAFE.union(safe)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000641
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000642 def __repr__(self):
643 # Without this, will just display as a defaultdict
644 return "<Quoter %r>" % dict(self)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000645
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000646 def __missing__(self, b):
647 # Handle a cache miss. Store quoted string in cache and return.
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000648 res = chr(b) if b in self.safe else '%{:02X}'.format(b)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000649 self[b] = res
650 return res
651
652def quote(string, safe='/', encoding=None, errors=None):
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000653 """quote('abc def') -> 'abc%20def'
654
655 Each part of a URL, e.g. the path info, the query, etc., has a
656 different set of reserved characters that must be quoted.
657
658 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
659 the following reserved characters.
660
661 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
662 "$" | ","
663
664 Each of these characters is reserved in some component of a URL,
665 but not necessarily in all of them.
666
667 By default, the quote function is intended for quoting the path
668 section of a URL. Thus, it will not encode '/'. This character
669 is reserved, but in typical usage the quote function is being
670 called on a path where the existing slash characters are used as
671 reserved characters.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000672
673 string and safe may be either str or bytes objects. encoding must
674 not be specified if string is a str.
675
676 The optional encoding and errors parameters specify how to deal with
677 non-ASCII characters, as accepted by the str.encode method.
678 By default, encoding='utf-8' (characters are encoded with UTF-8), and
679 errors='strict' (unsupported characters raise a UnicodeEncodeError).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000680 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000681 if isinstance(string, str):
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000682 if not string:
683 return string
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000684 if encoding is None:
685 encoding = 'utf-8'
686 if errors is None:
687 errors = 'strict'
688 string = string.encode(encoding, errors)
689 else:
690 if encoding is not None:
691 raise TypeError("quote() doesn't support 'encoding' for bytes")
692 if errors is not None:
693 raise TypeError("quote() doesn't support 'errors' for bytes")
694 return quote_from_bytes(string, safe)
695
696def quote_plus(string, safe='', encoding=None, errors=None):
697 """Like quote(), but also replace ' ' with '+', as required for quoting
698 HTML form values. Plus signs in the original string are escaped unless
699 they are included in safe. It also does not have safe default to '/'.
700 """
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000701 # Check if ' ' in string, where string may either be a str or bytes. If
702 # there are no spaces, the regular quote will produce the right answer.
703 if ((isinstance(string, str) and ' ' not in string) or
704 (isinstance(string, bytes) and b' ' not in string)):
705 return quote(string, safe, encoding, errors)
706 if isinstance(safe, str):
707 space = ' '
708 else:
709 space = b' '
Georg Brandlfaf41492009-05-26 18:31:11 +0000710 string = quote(string, safe + space, encoding, errors)
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000711 return string.replace(' ', '+')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000712
713def quote_from_bytes(bs, safe='/'):
714 """Like quote(), but accepts a bytes object rather than a str, and does
715 not perform string-to-bytes encoding. It always returns an ASCII string.
Senthil Kumaranffa4b2c2012-05-26 09:53:32 +0800716 quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000717 """
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000718 if not isinstance(bs, (bytes, bytearray)):
719 raise TypeError("quote_from_bytes() expected bytes")
720 if not bs:
721 return ''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000722 if isinstance(safe, str):
723 # Normalize 'safe' by converting to bytes and removing non-ASCII chars
724 safe = safe.encode('ascii', 'ignore')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000725 else:
726 safe = bytes([c for c in safe if c < 128])
727 if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
728 return bs.decode()
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000729 try:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000730 quoter = _safe_quoters[safe]
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000731 except KeyError:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000732 _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
733 return ''.join([quoter(char) for char in bs])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000734
Senthil Kumarandf022da2010-07-03 17:48:22 +0000735def urlencode(query, doseq=False, safe='', encoding=None, errors=None):
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700736 """Encode a dict or sequence of two-element tuples into a URL query string.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000737
738 If any values in the query arg are sequences and doseq is true, each
739 sequence element is converted to a separate parameter.
740
741 If the query arg is a sequence of two-element tuples, the order of the
742 parameters in the output will match the order of parameters in the
743 input.
Senthil Kumarandf022da2010-07-03 17:48:22 +0000744
Senthil Kumaran324ae3852013-09-05 21:42:38 -0700745 The components of a query arg may each be either a string or a bytes type.
746 When a component is a string, the safe, encoding and error parameters are
747 sent to the quote_plus function for encoding.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000748 """
749
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000750 if hasattr(query, "items"):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000751 query = query.items()
752 else:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000753 # It's a bother at times that strings and string-like objects are
754 # sequences.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000755 try:
756 # non-sequence items should not work with len()
757 # non-empty strings will fail this
758 if len(query) and not isinstance(query[0], tuple):
759 raise TypeError
Jeremy Hylton230feba2009-03-26 16:56:59 +0000760 # Zero-length sequences of all types will get here and succeed,
761 # but that's a minor nit. Since the original implementation
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000762 # allowed empty dicts that type of behavior probably should be
763 # preserved for consistency
764 except TypeError:
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000765 ty, va, tb = sys.exc_info()
766 raise TypeError("not a valid non-string sequence "
767 "or mapping object").with_traceback(tb)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000768
769 l = []
770 if not doseq:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000771 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000772 if isinstance(k, bytes):
773 k = quote_plus(k, safe)
774 else:
775 k = quote_plus(str(k), safe, encoding, errors)
776
777 if isinstance(v, bytes):
778 v = quote_plus(v, safe)
779 else:
780 v = quote_plus(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000781 l.append(k + '=' + v)
782 else:
783 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000784 if isinstance(k, bytes):
785 k = quote_plus(k, safe)
786 else:
787 k = quote_plus(str(k), safe, encoding, errors)
788
789 if isinstance(v, bytes):
790 v = quote_plus(v, safe)
791 l.append(k + '=' + v)
792 elif isinstance(v, str):
793 v = quote_plus(v, safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000794 l.append(k + '=' + v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000795 else:
796 try:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000797 # Is this a sufficient test for sequence-ness?
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000798 x = len(v)
799 except TypeError:
800 # not a sequence
Senthil Kumarandf022da2010-07-03 17:48:22 +0000801 v = quote_plus(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000802 l.append(k + '=' + v)
803 else:
804 # loop over the sequence
805 for elt in v:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000806 if isinstance(elt, bytes):
807 elt = quote_plus(elt, safe)
808 else:
809 elt = quote_plus(str(elt), safe, encoding, errors)
810 l.append(k + '=' + elt)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000811 return '&'.join(l)
812
813# Utilities to parse URLs (most of these return None for missing parts):
814# unwrap('<URL:type://host/path>') --> 'type://host/path'
815# splittype('type:opaquestring') --> 'type', 'opaquestring'
816# splithost('//host[:port]/path') --> 'host[:port]', '/path'
817# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
818# splitpasswd('user:passwd') -> 'user', 'passwd'
819# splitport('host:port') --> 'host', 'port'
820# splitquery('/path?query') --> '/path', 'query'
821# splittag('/path#tag') --> '/path', 'tag'
822# splitattr('/path;attr1=value1;attr2=value2;...') ->
823# '/path', ['attr1=value1', 'attr2=value2', ...]
824# splitvalue('attr=value') --> 'attr', 'value'
825# urllib.parse.unquote('abc%20def') -> 'abc def'
826# quote('abc def') -> 'abc%20def')
827
Georg Brandl13e89462008-07-01 19:56:00 +0000828def to_bytes(url):
829 """to_bytes(u"URL") --> 'URL'."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000830 # Most URL schemes require ASCII. If that changes, the conversion
831 # can be relaxed.
Georg Brandl13e89462008-07-01 19:56:00 +0000832 # XXX get rid of to_bytes()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000833 if isinstance(url, str):
834 try:
835 url = url.encode("ASCII").decode()
836 except UnicodeError:
837 raise UnicodeError("URL " + repr(url) +
838 " contains non-ASCII characters")
839 return url
840
841def unwrap(url):
842 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
843 url = str(url).strip()
844 if url[:1] == '<' and url[-1:] == '>':
845 url = url[1:-1].strip()
846 if url[:4] == 'URL:': url = url[4:].strip()
847 return url
848
849_typeprog = None
850def splittype(url):
851 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
852 global _typeprog
853 if _typeprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000854 _typeprog = re.compile('^([^/:]+):')
855
856 match = _typeprog.match(url)
857 if match:
858 scheme = match.group(1)
859 return scheme.lower(), url[len(scheme) + 1:]
860 return None, url
861
862_hostprog = None
863def splithost(url):
864 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
865 global _hostprog
866 if _hostprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000867 _hostprog = re.compile('^//([^/?]*)(.*)$')
868
869 match = _hostprog.match(url)
Senthil Kumaranc2958622010-11-22 04:48:26 +0000870 if match:
871 host_port = match.group(1)
872 path = match.group(2)
873 if path and not path.startswith('/'):
874 path = '/' + path
875 return host_port, path
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000876 return None, url
877
878_userprog = None
879def splituser(host):
880 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
881 global _userprog
882 if _userprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000883 _userprog = re.compile('^(.*)@(.*)$')
884
885 match = _userprog.match(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000886 if match: return match.group(1, 2)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000887 return None, host
888
889_passwdprog = None
890def splitpasswd(user):
891 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
892 global _passwdprog
893 if _passwdprog is None:
Senthil Kumaraneaaec272009-03-30 21:54:41 +0000894 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000895
896 match = _passwdprog.match(user)
897 if match: return match.group(1, 2)
898 return user, None
899
900# splittag('/path#tag') --> '/path', 'tag'
901_portprog = None
902def splitport(host):
903 """splitport('host:port') --> 'host', 'port'."""
904 global _portprog
905 if _portprog is None:
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200906 _portprog = re.compile('^(.*):([0-9]*)$')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000907
908 match = _portprog.match(host)
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200909 if match:
910 host, port = match.groups()
911 if port:
912 return host, port
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000913 return host, None
914
915_nportprog = None
916def splitnport(host, defport=-1):
917 """Split host and port, returning numeric port.
918 Return given default port if no ':' found; defaults to -1.
919 Return numerical port if a valid number are found after ':'.
920 Return None if ':' but not a valid number."""
921 global _nportprog
922 if _nportprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000923 _nportprog = re.compile('^(.*):(.*)$')
924
925 match = _nportprog.match(host)
926 if match:
927 host, port = match.group(1, 2)
Serhiy Storchakaff97b082014-01-18 18:30:33 +0200928 if port:
929 try:
930 nport = int(port)
931 except ValueError:
932 nport = None
933 return host, nport
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000934 return host, defport
935
936_queryprog = None
937def splitquery(url):
938 """splitquery('/path?query') --> '/path', 'query'."""
939 global _queryprog
940 if _queryprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000941 _queryprog = re.compile('^(.*)\?([^?]*)$')
942
943 match = _queryprog.match(url)
944 if match: return match.group(1, 2)
945 return url, None
946
947_tagprog = None
948def splittag(url):
949 """splittag('/path#tag') --> '/path', 'tag'."""
950 global _tagprog
951 if _tagprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000952 _tagprog = re.compile('^(.*)#([^#]*)$')
953
954 match = _tagprog.match(url)
955 if match: return match.group(1, 2)
956 return url, None
957
958def splitattr(url):
959 """splitattr('/path;attr1=value1;attr2=value2;...') ->
960 '/path', ['attr1=value1', 'attr2=value2', ...]."""
961 words = url.split(';')
962 return words[0], words[1:]
963
964_valueprog = None
965def splitvalue(attr):
966 """splitvalue('attr=value') --> 'attr', 'value'."""
967 global _valueprog
968 if _valueprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000969 _valueprog = re.compile('^([^=]*)=(.*)$')
970
971 match = _valueprog.match(attr)
972 if match: return match.group(1, 2)
973 return attr, None