blob: b49b7a1f26fd454a91629feef96b1edacdd30bd3 [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(']')
185 _, have_port, port = port.partition(':')
186 else:
187 hostname, have_port, port = hostinfo.partition(':')
188 if not have_port:
189 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']')
215 _, have_port, port = port.partition(b':')
216 else:
217 hostname, have_port, port = hostinfo.partition(b':')
218 if not have_port:
219 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'
475_hextobyte = {(a + b).encode(): bytes([int(a + b, 16)])
476 for a in _hexdig for b in _hexdig}
477
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000478def unquote_to_bytes(string):
479 """unquote_to_bytes('abc%20def') -> b'abc def'."""
480 # Note: strings are encoded as UTF-8. This is only an issue if it contains
481 # unescaped non-ASCII characters, which URIs should not.
Florent Xicluna82a3f8a2010-08-14 18:30:35 +0000482 if not string:
483 # Is it a string-like object?
484 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000485 return b''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000486 if isinstance(string, str):
487 string = string.encode('utf-8')
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200488 bits = string.split(b'%')
489 if len(bits) == 1:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000490 return string
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200491 res = [bits[0]]
492 append = res.append
493 for item in bits[1:]:
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000494 try:
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200495 append(_hextobyte[item[:2]])
496 append(item[2:])
497 except KeyError:
498 append(b'%')
499 append(item)
500 return b''.join(res)
501
502_asciire = re.compile('([\x00-\x7f]+)')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000503
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000504def unquote(string, encoding='utf-8', errors='replace'):
505 """Replace %xx escapes by their single-character equivalent. The optional
506 encoding and errors parameters specify how to decode percent-encoded
507 sequences into Unicode characters, as accepted by the bytes.decode()
508 method.
509 By default, percent-encoded sequences are decoded with UTF-8, and invalid
510 sequences are replaced by a placeholder character.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000511
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000512 unquote('abc%20def') -> 'abc def'.
513 """
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200514 if '%' not in string:
515 string.split
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000516 return string
517 if encoding is None:
518 encoding = 'utf-8'
519 if errors is None:
520 errors = 'replace'
Serhiy Storchaka8ea46162013-03-14 21:31:37 +0200521 bits = _asciire.split(string)
522 res = [bits[0]]
523 append = res.append
524 for i in range(1, len(bits), 2):
525 append(unquote_to_bytes(bits[i]).decode(encoding, errors))
526 append(bits[i + 1])
527 return ''.join(res)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000528
Victor Stinnerac71c542011-01-14 12:52:12 +0000529def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
530 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000531 """Parse a query given as a string argument.
532
533 Arguments:
534
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000535 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000536
537 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000538 percent-encoded queries should be treated as blank strings.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000539 A true value indicates that blanks should be retained as
540 blank strings. The default false value indicates that
541 blank values are to be ignored and treated as if they were
542 not included.
543
544 strict_parsing: flag indicating what to do with parsing errors.
545 If false (the default), errors are silently ignored.
546 If true, errors raise a ValueError exception.
Victor Stinnerac71c542011-01-14 12:52:12 +0000547
548 encoding and errors: specify how to decode percent-encoded sequences
549 into Unicode characters, as accepted by the bytes.decode() method.
Facundo Batistac469d4c2008-09-03 22:49:01 +0000550 """
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700551 parsed_result = {}
Victor Stinnerac71c542011-01-14 12:52:12 +0000552 pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
553 encoding=encoding, errors=errors)
554 for name, value in pairs:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700555 if name in parsed_result:
556 parsed_result[name].append(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000557 else:
Senthil Kumaraneda29f42012-06-29 11:08:20 -0700558 parsed_result[name] = [value]
559 return parsed_result
Facundo Batistac469d4c2008-09-03 22:49:01 +0000560
Victor Stinnerac71c542011-01-14 12:52:12 +0000561def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
562 encoding='utf-8', errors='replace'):
Facundo Batistac469d4c2008-09-03 22:49:01 +0000563 """Parse a query given as a string argument.
564
565 Arguments:
566
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000567 qs: percent-encoded query string to be parsed
Facundo Batistac469d4c2008-09-03 22:49:01 +0000568
569 keep_blank_values: flag indicating whether blank values in
Senthil Kumaran30e86a42010-08-09 20:01:35 +0000570 percent-encoded queries should be treated as blank strings. A
Facundo Batistac469d4c2008-09-03 22:49:01 +0000571 true value indicates that blanks should be retained as blank
572 strings. The default false value indicates that blank values
573 are to be ignored and treated as if they were not included.
574
575 strict_parsing: flag indicating what to do with parsing errors. If
576 false (the default), errors are silently ignored. If true,
577 errors raise a ValueError exception.
578
Victor Stinnerac71c542011-01-14 12:52:12 +0000579 encoding and errors: specify how to decode percent-encoded sequences
580 into Unicode characters, as accepted by the bytes.decode() method.
581
Facundo Batistac469d4c2008-09-03 22:49:01 +0000582 Returns a list, as G-d intended.
583 """
Nick Coghlan9fc443c2010-11-30 15:48:08 +0000584 qs, _coerce_result = _coerce_args(qs)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000585 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
586 r = []
587 for name_value in pairs:
588 if not name_value and not strict_parsing:
589 continue
590 nv = name_value.split('=', 1)
591 if len(nv) != 2:
592 if strict_parsing:
593 raise ValueError("bad query field: %r" % (name_value,))
594 # Handle case of a control-name with no equal sign
595 if keep_blank_values:
596 nv.append('')
597 else:
598 continue
599 if len(nv[1]) or keep_blank_values:
Victor Stinnerac71c542011-01-14 12:52:12 +0000600 name = nv[0].replace('+', ' ')
601 name = unquote(name, encoding=encoding, errors=errors)
602 name = _coerce_result(name)
603 value = nv[1].replace('+', ' ')
604 value = unquote(value, encoding=encoding, errors=errors)
605 value = _coerce_result(value)
Facundo Batistac469d4c2008-09-03 22:49:01 +0000606 r.append((name, value))
Facundo Batistac469d4c2008-09-03 22:49:01 +0000607 return r
608
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000609def unquote_plus(string, encoding='utf-8', errors='replace'):
610 """Like unquote(), but also replace plus signs by spaces, as required for
611 unquoting HTML form values.
612
613 unquote_plus('%7e/abc+def') -> '~/abc def'
614 """
615 string = string.replace('+', ' ')
616 return unquote(string, encoding, errors)
617
618_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
619 b'abcdefghijklmnopqrstuvwxyz'
620 b'0123456789'
621 b'_.-')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000622_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
623_safe_quoters = {}
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000624
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000625class Quoter(collections.defaultdict):
626 """A mapping from bytes (in range(0,256)) to strings.
627
628 String values are percent-encoded byte values, unless the key < 128, and
629 in the "safe" set (either the specified safe set, or default set).
630 """
631 # Keeps a cache internally, using defaultdict, for efficiency (lookups
632 # of cached keys don't call Python code at all).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000633 def __init__(self, safe):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000634 """safe: bytes object."""
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000635 self.safe = _ALWAYS_SAFE.union(safe)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000636
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000637 def __repr__(self):
638 # Without this, will just display as a defaultdict
639 return "<Quoter %r>" % dict(self)
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000640
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000641 def __missing__(self, b):
642 # Handle a cache miss. Store quoted string in cache and return.
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000643 res = chr(b) if b in self.safe else '%{:02X}'.format(b)
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000644 self[b] = res
645 return res
646
647def quote(string, safe='/', encoding=None, errors=None):
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000648 """quote('abc def') -> 'abc%20def'
649
650 Each part of a URL, e.g. the path info, the query, etc., has a
651 different set of reserved characters that must be quoted.
652
653 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
654 the following reserved characters.
655
656 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
657 "$" | ","
658
659 Each of these characters is reserved in some component of a URL,
660 but not necessarily in all of them.
661
662 By default, the quote function is intended for quoting the path
663 section of a URL. Thus, it will not encode '/'. This character
664 is reserved, but in typical usage the quote function is being
665 called on a path where the existing slash characters are used as
666 reserved characters.
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000667
668 string and safe may be either str or bytes objects. encoding must
669 not be specified if string is a str.
670
671 The optional encoding and errors parameters specify how to deal with
672 non-ASCII characters, as accepted by the str.encode method.
673 By default, encoding='utf-8' (characters are encoded with UTF-8), and
674 errors='strict' (unsupported characters raise a UnicodeEncodeError).
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000675 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000676 if isinstance(string, str):
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000677 if not string:
678 return string
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000679 if encoding is None:
680 encoding = 'utf-8'
681 if errors is None:
682 errors = 'strict'
683 string = string.encode(encoding, errors)
684 else:
685 if encoding is not None:
686 raise TypeError("quote() doesn't support 'encoding' for bytes")
687 if errors is not None:
688 raise TypeError("quote() doesn't support 'errors' for bytes")
689 return quote_from_bytes(string, safe)
690
691def quote_plus(string, safe='', encoding=None, errors=None):
692 """Like quote(), but also replace ' ' with '+', as required for quoting
693 HTML form values. Plus signs in the original string are escaped unless
694 they are included in safe. It also does not have safe default to '/'.
695 """
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000696 # Check if ' ' in string, where string may either be a str or bytes. If
697 # there are no spaces, the regular quote will produce the right answer.
698 if ((isinstance(string, str) and ' ' not in string) or
699 (isinstance(string, bytes) and b' ' not in string)):
700 return quote(string, safe, encoding, errors)
701 if isinstance(safe, str):
702 space = ' '
703 else:
704 space = b' '
Georg Brandlfaf41492009-05-26 18:31:11 +0000705 string = quote(string, safe + space, encoding, errors)
Jeremy Hyltonf8198862009-03-26 16:55:08 +0000706 return string.replace(' ', '+')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000707
708def quote_from_bytes(bs, safe='/'):
709 """Like quote(), but accepts a bytes object rather than a str, and does
710 not perform string-to-bytes encoding. It always returns an ASCII string.
Senthil Kumaranffa4b2c2012-05-26 09:53:32 +0800711 quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000712 """
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000713 if not isinstance(bs, (bytes, bytearray)):
714 raise TypeError("quote_from_bytes() expected bytes")
715 if not bs:
716 return ''
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000717 if isinstance(safe, str):
718 # Normalize 'safe' by converting to bytes and removing non-ASCII chars
719 safe = safe.encode('ascii', 'ignore')
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000720 else:
721 safe = bytes([c for c in safe if c < 128])
722 if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
723 return bs.decode()
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000724 try:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000725 quoter = _safe_quoters[safe]
Guido van Rossumdf9f1ec2008-08-06 19:31:34 +0000726 except KeyError:
Florent Xiclunac7b8e862010-05-17 17:33:07 +0000727 _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
728 return ''.join([quoter(char) for char in bs])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000729
Senthil Kumarandf022da2010-07-03 17:48:22 +0000730def urlencode(query, doseq=False, safe='', encoding=None, errors=None):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000731 """Encode a sequence of two-element tuples or dictionary into a URL query string.
732
733 If any values in the query arg are sequences and doseq is true, each
734 sequence element is converted to a separate parameter.
735
736 If the query arg is a sequence of two-element tuples, the order of the
737 parameters in the output will match the order of parameters in the
738 input.
Senthil Kumarandf022da2010-07-03 17:48:22 +0000739
740 The query arg may be either a string or a bytes type. When query arg is a
741 string, the safe, encoding and error parameters are sent the quote_plus for
742 encoding.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000743 """
744
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000745 if hasattr(query, "items"):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000746 query = query.items()
747 else:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000748 # It's a bother at times that strings and string-like objects are
749 # sequences.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000750 try:
751 # non-sequence items should not work with len()
752 # non-empty strings will fail this
753 if len(query) and not isinstance(query[0], tuple):
754 raise TypeError
Jeremy Hylton230feba2009-03-26 16:56:59 +0000755 # Zero-length sequences of all types will get here and succeed,
756 # but that's a minor nit. Since the original implementation
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000757 # allowed empty dicts that type of behavior probably should be
758 # preserved for consistency
759 except TypeError:
Jeremy Hyltona4de60a2009-03-26 14:49:26 +0000760 ty, va, tb = sys.exc_info()
761 raise TypeError("not a valid non-string sequence "
762 "or mapping object").with_traceback(tb)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000763
764 l = []
765 if not doseq:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000766 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000767 if isinstance(k, bytes):
768 k = quote_plus(k, safe)
769 else:
770 k = quote_plus(str(k), safe, encoding, errors)
771
772 if isinstance(v, bytes):
773 v = quote_plus(v, safe)
774 else:
775 v = quote_plus(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000776 l.append(k + '=' + v)
777 else:
778 for k, v in query:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000779 if isinstance(k, bytes):
780 k = quote_plus(k, safe)
781 else:
782 k = quote_plus(str(k), safe, encoding, errors)
783
784 if isinstance(v, bytes):
785 v = quote_plus(v, safe)
786 l.append(k + '=' + v)
787 elif isinstance(v, str):
788 v = quote_plus(v, safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000789 l.append(k + '=' + v)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000790 else:
791 try:
Jeremy Hylton230feba2009-03-26 16:56:59 +0000792 # Is this a sufficient test for sequence-ness?
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000793 x = len(v)
794 except TypeError:
795 # not a sequence
Senthil Kumarandf022da2010-07-03 17:48:22 +0000796 v = quote_plus(str(v), safe, encoding, errors)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000797 l.append(k + '=' + v)
798 else:
799 # loop over the sequence
800 for elt in v:
Senthil Kumarandf022da2010-07-03 17:48:22 +0000801 if isinstance(elt, bytes):
802 elt = quote_plus(elt, safe)
803 else:
804 elt = quote_plus(str(elt), safe, encoding, errors)
805 l.append(k + '=' + elt)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000806 return '&'.join(l)
807
808# Utilities to parse URLs (most of these return None for missing parts):
809# unwrap('<URL:type://host/path>') --> 'type://host/path'
810# splittype('type:opaquestring') --> 'type', 'opaquestring'
811# splithost('//host[:port]/path') --> 'host[:port]', '/path'
812# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
813# splitpasswd('user:passwd') -> 'user', 'passwd'
814# splitport('host:port') --> 'host', 'port'
815# splitquery('/path?query') --> '/path', 'query'
816# splittag('/path#tag') --> '/path', 'tag'
817# splitattr('/path;attr1=value1;attr2=value2;...') ->
818# '/path', ['attr1=value1', 'attr2=value2', ...]
819# splitvalue('attr=value') --> 'attr', 'value'
820# urllib.parse.unquote('abc%20def') -> 'abc def'
821# quote('abc def') -> 'abc%20def')
822
Georg Brandl13e89462008-07-01 19:56:00 +0000823def to_bytes(url):
824 """to_bytes(u"URL") --> 'URL'."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000825 # Most URL schemes require ASCII. If that changes, the conversion
826 # can be relaxed.
Georg Brandl13e89462008-07-01 19:56:00 +0000827 # XXX get rid of to_bytes()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000828 if isinstance(url, str):
829 try:
830 url = url.encode("ASCII").decode()
831 except UnicodeError:
832 raise UnicodeError("URL " + repr(url) +
833 " contains non-ASCII characters")
834 return url
835
836def unwrap(url):
837 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
838 url = str(url).strip()
839 if url[:1] == '<' and url[-1:] == '>':
840 url = url[1:-1].strip()
841 if url[:4] == 'URL:': url = url[4:].strip()
842 return url
843
844_typeprog = None
845def splittype(url):
846 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
847 global _typeprog
848 if _typeprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000849 _typeprog = re.compile('^([^/:]+):')
850
851 match = _typeprog.match(url)
852 if match:
853 scheme = match.group(1)
854 return scheme.lower(), url[len(scheme) + 1:]
855 return None, url
856
857_hostprog = None
858def splithost(url):
859 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
860 global _hostprog
861 if _hostprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000862 _hostprog = re.compile('^//([^/?]*)(.*)$')
863
864 match = _hostprog.match(url)
Senthil Kumaranc2958622010-11-22 04:48:26 +0000865 if match:
866 host_port = match.group(1)
867 path = match.group(2)
868 if path and not path.startswith('/'):
869 path = '/' + path
870 return host_port, path
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000871 return None, url
872
873_userprog = None
874def splituser(host):
875 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
876 global _userprog
877 if _userprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000878 _userprog = re.compile('^(.*)@(.*)$')
879
880 match = _userprog.match(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000881 if match: return match.group(1, 2)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000882 return None, host
883
884_passwdprog = None
885def splitpasswd(user):
886 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
887 global _passwdprog
888 if _passwdprog is None:
Senthil Kumaraneaaec272009-03-30 21:54:41 +0000889 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000890
891 match = _passwdprog.match(user)
892 if match: return match.group(1, 2)
893 return user, None
894
895# splittag('/path#tag') --> '/path', 'tag'
896_portprog = None
897def splitport(host):
898 """splitport('host:port') --> 'host', 'port'."""
899 global _portprog
900 if _portprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000901 _portprog = re.compile('^(.*):([0-9]+)$')
902
903 match = _portprog.match(host)
904 if match: return match.group(1, 2)
905 return host, None
906
907_nportprog = None
908def splitnport(host, defport=-1):
909 """Split host and port, returning numeric port.
910 Return given default port if no ':' found; defaults to -1.
911 Return numerical port if a valid number are found after ':'.
912 Return None if ':' but not a valid number."""
913 global _nportprog
914 if _nportprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000915 _nportprog = re.compile('^(.*):(.*)$')
916
917 match = _nportprog.match(host)
918 if match:
919 host, port = match.group(1, 2)
920 try:
921 if not port: raise ValueError("no digits")
922 nport = int(port)
923 except ValueError:
924 nport = None
925 return host, nport
926 return host, defport
927
928_queryprog = None
929def splitquery(url):
930 """splitquery('/path?query') --> '/path', 'query'."""
931 global _queryprog
932 if _queryprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000933 _queryprog = re.compile('^(.*)\?([^?]*)$')
934
935 match = _queryprog.match(url)
936 if match: return match.group(1, 2)
937 return url, None
938
939_tagprog = None
940def splittag(url):
941 """splittag('/path#tag') --> '/path', 'tag'."""
942 global _tagprog
943 if _tagprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000944 _tagprog = re.compile('^(.*)#([^#]*)$')
945
946 match = _tagprog.match(url)
947 if match: return match.group(1, 2)
948 return url, None
949
950def splitattr(url):
951 """splitattr('/path;attr1=value1;attr2=value2;...') ->
952 '/path', ['attr1=value1', 'attr2=value2', ...]."""
953 words = url.split(';')
954 return words[0], words[1:]
955
956_valueprog = None
957def splitvalue(attr):
958 """splitvalue('attr=value') --> 'attr', 'value'."""
959 global _valueprog
960 if _valueprog is None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000961 _valueprog = re.compile('^([^=]*)=(.*)$')
962
963 match = _valueprog.match(attr)
964 if match: return match.group(1, 2)
965 return attr, None