Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1 | """Parse (absolute and relative) URLs. |
| 2 | |
Senthil Kumaran | fd41e08 | 2010-04-17 14:44:14 +0000 | [diff] [blame] | 3 | urlparse module is based upon the following RFC specifications. |
| 4 | |
| 5 | RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding |
| 6 | and L. Masinter, January 2005. |
| 7 | |
| 8 | RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter |
| 9 | and L.Masinter, December 1999. |
| 10 | |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 11 | RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. |
Senthil Kumaran | fd41e08 | 2010-04-17 14:44:14 +0000 | [diff] [blame] | 12 | Berners-Lee, R. Fielding, and L. Masinter, August 1998. |
| 13 | |
David Malcolm | ee25568 | 2010-12-02 16:41:00 +0000 | [diff] [blame] | 14 | RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998. |
Senthil Kumaran | fd41e08 | 2010-04-17 14:44:14 +0000 | [diff] [blame] | 15 | |
| 16 | RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June |
| 17 | 1995. |
| 18 | |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 19 | RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. |
Senthil Kumaran | fd41e08 | 2010-04-17 14:44:14 +0000 | [diff] [blame] | 20 | McCahill, December 1994 |
| 21 | |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 22 | RFC 3986 is considered the current standard and any future changes to |
| 23 | urlparse module should conform with it. The urlparse module is |
| 24 | currently not entirely compliant with this RFC due to defacto |
| 25 | scenarios for parsing, and for backward compatibility purposes, some |
| 26 | parsing quirks from older RFCs are retained. The testcases in |
Senthil Kumaran | fd41e08 | 2010-04-17 14:44:14 +0000 | [diff] [blame] | 27 | test_urlparse.py provides a good indicator of parsing behavior. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 28 | """ |
| 29 | |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 30 | import re |
Facundo Batista | 2ac5de2 | 2008-07-07 18:24:11 +0000 | [diff] [blame] | 31 | import sys |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 32 | import collections |
Facundo Batista | 2ac5de2 | 2008-07-07 18:24:11 +0000 | [diff] [blame] | 33 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 34 | __all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag", |
Senthil Kumaran | 0256b2a | 2010-10-25 16:36:20 +0000 | [diff] [blame] | 35 | "urlsplit", "urlunsplit", "urlencode", "parse_qs", |
| 36 | "parse_qsl", "quote", "quote_plus", "quote_from_bytes", |
Serhiy Storchaka | 1515450 | 2015-04-07 19:09:01 +0300 | [diff] [blame] | 37 | "unquote", "unquote_plus", "unquote_to_bytes", |
| 38 | "DefragResult", "ParseResult", "SplitResult", |
| 39 | "DefragResultBytes", "ParseResultBytes", "SplitResultBytes"] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 40 | |
| 41 | # A classification of schemes ('' means apply by default) |
| 42 | uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'imap', |
| 43 | 'wais', 'file', 'https', 'shttp', 'mms', |
Senthil Kumaran | 2a157d2 | 2011-08-03 18:37:22 +0800 | [diff] [blame] | 44 | 'prospero', 'rtsp', 'rtspu', '', 'sftp', |
| 45 | 'svn', 'svn+ssh'] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 46 | uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', |
| 47 | 'imap', 'wais', 'file', 'mms', 'https', 'shttp', |
| 48 | 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 49 | 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh'] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 50 | uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', |
| 51 | 'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips', |
Senthil Kumaran | ed30199 | 2012-12-24 14:00:20 -0800 | [diff] [blame] | 52 | 'mms', '', 'sftp', 'tel'] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 53 | |
Georg Brandl | a61b09f | 2012-08-24 18:15:29 +0200 | [diff] [blame] | 54 | # These are not actually used anymore, but should stay for backwards |
| 55 | # compatibility. (They are undocumented, but have a public-looking name.) |
| 56 | non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', |
| 57 | 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] |
| 58 | uses_query = ['http', 'wais', 'imap', 'https', 'shttp', 'mms', |
| 59 | 'gopher', 'rtsp', 'rtspu', 'sip', 'sips', ''] |
| 60 | uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news', |
| 61 | 'nntp', 'wais', 'https', 'shttp', 'snews', |
| 62 | 'file', 'prospero', ''] |
| 63 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 64 | # Characters valid in scheme names |
| 65 | scheme_chars = ('abcdefghijklmnopqrstuvwxyz' |
| 66 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 67 | '0123456789' |
| 68 | '+-.') |
| 69 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 70 | # XXX: Consider replacing with functools.lru_cache |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 71 | MAX_CACHE_SIZE = 20 |
| 72 | _parse_cache = {} |
| 73 | |
| 74 | def clear_cache(): |
Antoine Pitrou | 2df5fc7 | 2009-12-08 19:38:17 +0000 | [diff] [blame] | 75 | """Clear the parse cache and the quoters cache.""" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 76 | _parse_cache.clear() |
Antoine Pitrou | 2df5fc7 | 2009-12-08 19:38:17 +0000 | [diff] [blame] | 77 | _safe_quoters.clear() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 78 | |
| 79 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 80 | # Helpers for bytes handling |
| 81 | # For 3.2, we deliberately require applications that |
| 82 | # handle improperly quoted URLs to do their own |
| 83 | # decoding and encoding. If valid use cases are |
| 84 | # presented, we may relax this by using latin-1 |
| 85 | # decoding internally for 3.3 |
| 86 | _implicit_encoding = 'ascii' |
| 87 | _implicit_errors = 'strict' |
| 88 | |
| 89 | def _noop(obj): |
| 90 | return obj |
| 91 | |
| 92 | def _encode_result(obj, encoding=_implicit_encoding, |
| 93 | errors=_implicit_errors): |
| 94 | return obj.encode(encoding, errors) |
| 95 | |
| 96 | def _decode_args(args, encoding=_implicit_encoding, |
| 97 | errors=_implicit_errors): |
| 98 | return tuple(x.decode(encoding, errors) if x else '' for x in args) |
| 99 | |
| 100 | def _coerce_args(*args): |
| 101 | # Invokes decode if necessary to create str args |
| 102 | # and returns the coerced inputs along with |
| 103 | # an appropriate result coercion function |
| 104 | # - noop for str inputs |
| 105 | # - encoding function otherwise |
| 106 | str_input = isinstance(args[0], str) |
| 107 | for arg in args[1:]: |
| 108 | # We special-case the empty string to support the |
| 109 | # "scheme=''" default argument to some functions |
| 110 | if arg and isinstance(arg, str) != str_input: |
| 111 | raise TypeError("Cannot mix str and non-str arguments") |
| 112 | if str_input: |
| 113 | return args + (_noop,) |
| 114 | return _decode_args(args) + (_encode_result,) |
| 115 | |
| 116 | # Result objects are more helpful than simple tuples |
| 117 | class _ResultMixinStr(object): |
| 118 | """Standard approach to encoding parsed results from str to bytes""" |
| 119 | __slots__ = () |
| 120 | |
| 121 | def encode(self, encoding='ascii', errors='strict'): |
| 122 | return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self)) |
| 123 | |
| 124 | |
| 125 | class _ResultMixinBytes(object): |
| 126 | """Standard approach to decoding parsed results from bytes to str""" |
| 127 | __slots__ = () |
| 128 | |
| 129 | def decode(self, encoding='ascii', errors='strict'): |
| 130 | return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self)) |
| 131 | |
| 132 | |
| 133 | class _NetlocResultMixinBase(object): |
| 134 | """Shared methods for the parsed result objects containing a netloc element""" |
| 135 | __slots__ = () |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 136 | |
| 137 | @property |
| 138 | def username(self): |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 139 | return self._userinfo[0] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 140 | |
| 141 | @property |
| 142 | def password(self): |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 143 | return self._userinfo[1] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 144 | |
| 145 | @property |
| 146 | def hostname(self): |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 147 | hostname = self._hostinfo[0] |
| 148 | if not hostname: |
| 149 | hostname = None |
| 150 | elif hostname is not None: |
| 151 | hostname = hostname.lower() |
| 152 | return hostname |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 153 | |
| 154 | @property |
| 155 | def port(self): |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 156 | port = self._hostinfo[1] |
| 157 | if port is not None: |
| 158 | port = int(port, 10) |
Senthil Kumaran | 2fc5a50 | 2012-05-24 21:56:17 +0800 | [diff] [blame] | 159 | # Return None on an illegal port |
| 160 | if not ( 0 <= port <= 65535): |
| 161 | return None |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 162 | return port |
| 163 | |
| 164 | |
| 165 | class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr): |
| 166 | __slots__ = () |
| 167 | |
| 168 | @property |
| 169 | def _userinfo(self): |
| 170 | netloc = self.netloc |
| 171 | userinfo, have_info, hostinfo = netloc.rpartition('@') |
| 172 | if have_info: |
| 173 | username, have_password, password = userinfo.partition(':') |
| 174 | if not have_password: |
| 175 | password = None |
Senthil Kumaran | ad02d23 | 2010-04-16 03:02:13 +0000 | [diff] [blame] | 176 | else: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 177 | username = password = None |
| 178 | return username, password |
| 179 | |
| 180 | @property |
| 181 | def _hostinfo(self): |
| 182 | netloc = self.netloc |
| 183 | _, _, hostinfo = netloc.rpartition('@') |
| 184 | _, have_open_br, bracketed = hostinfo.partition('[') |
| 185 | if have_open_br: |
| 186 | hostname, _, port = bracketed.partition(']') |
Serhiy Storchaka | ff97b08 | 2014-01-18 18:30:33 +0200 | [diff] [blame] | 187 | _, _, port = port.partition(':') |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 188 | else: |
Serhiy Storchaka | ff97b08 | 2014-01-18 18:30:33 +0200 | [diff] [blame] | 189 | hostname, _, port = hostinfo.partition(':') |
| 190 | if not port: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 191 | port = None |
| 192 | return hostname, port |
| 193 | |
| 194 | |
| 195 | class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes): |
| 196 | __slots__ = () |
| 197 | |
| 198 | @property |
| 199 | def _userinfo(self): |
| 200 | netloc = self.netloc |
| 201 | userinfo, have_info, hostinfo = netloc.rpartition(b'@') |
| 202 | if have_info: |
| 203 | username, have_password, password = userinfo.partition(b':') |
| 204 | if not have_password: |
| 205 | password = None |
| 206 | else: |
| 207 | username = password = None |
| 208 | return username, password |
| 209 | |
| 210 | @property |
| 211 | def _hostinfo(self): |
| 212 | netloc = self.netloc |
| 213 | _, _, hostinfo = netloc.rpartition(b'@') |
| 214 | _, have_open_br, bracketed = hostinfo.partition(b'[') |
| 215 | if have_open_br: |
| 216 | hostname, _, port = bracketed.partition(b']') |
Serhiy Storchaka | ff97b08 | 2014-01-18 18:30:33 +0200 | [diff] [blame] | 217 | _, _, port = port.partition(b':') |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 218 | else: |
Serhiy Storchaka | ff97b08 | 2014-01-18 18:30:33 +0200 | [diff] [blame] | 219 | hostname, _, port = hostinfo.partition(b':') |
| 220 | if not port: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 221 | port = None |
| 222 | return hostname, port |
| 223 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 224 | |
| 225 | from collections import namedtuple |
| 226 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 227 | _DefragResultBase = namedtuple('DefragResult', 'url fragment') |
| 228 | _SplitResultBase = namedtuple('SplitResult', 'scheme netloc path query fragment') |
| 229 | _ParseResultBase = namedtuple('ParseResult', 'scheme netloc path params query fragment') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 230 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 231 | # For backwards compatibility, alias _NetlocResultMixinStr |
| 232 | # ResultBase is no longer part of the documented API, but it is |
| 233 | # retained since deprecating it isn't worth the hassle |
| 234 | ResultBase = _NetlocResultMixinStr |
| 235 | |
| 236 | # Structured result objects for string data |
| 237 | class DefragResult(_DefragResultBase, _ResultMixinStr): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 238 | __slots__ = () |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 239 | def geturl(self): |
| 240 | if self.fragment: |
| 241 | return self.url + '#' + self.fragment |
| 242 | else: |
| 243 | return self.url |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 244 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 245 | class SplitResult(_SplitResultBase, _NetlocResultMixinStr): |
| 246 | __slots__ = () |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 247 | def geturl(self): |
| 248 | return urlunsplit(self) |
| 249 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 250 | class ParseResult(_ParseResultBase, _NetlocResultMixinStr): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 251 | __slots__ = () |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 252 | def geturl(self): |
| 253 | return urlunparse(self) |
| 254 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 255 | # Structured result objects for bytes data |
| 256 | class DefragResultBytes(_DefragResultBase, _ResultMixinBytes): |
| 257 | __slots__ = () |
| 258 | def geturl(self): |
| 259 | if self.fragment: |
| 260 | return self.url + b'#' + self.fragment |
| 261 | else: |
| 262 | return self.url |
| 263 | |
| 264 | class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes): |
| 265 | __slots__ = () |
| 266 | def geturl(self): |
| 267 | return urlunsplit(self) |
| 268 | |
| 269 | class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes): |
| 270 | __slots__ = () |
| 271 | def geturl(self): |
| 272 | return urlunparse(self) |
| 273 | |
| 274 | # Set up the encode/decode result pairs |
| 275 | def _fix_result_transcoding(): |
| 276 | _result_pairs = ( |
| 277 | (DefragResult, DefragResultBytes), |
| 278 | (SplitResult, SplitResultBytes), |
| 279 | (ParseResult, ParseResultBytes), |
| 280 | ) |
| 281 | for _decoded, _encoded in _result_pairs: |
| 282 | _decoded._encoded_counterpart = _encoded |
| 283 | _encoded._decoded_counterpart = _decoded |
| 284 | |
| 285 | _fix_result_transcoding() |
| 286 | del _fix_result_transcoding |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 287 | |
| 288 | def urlparse(url, scheme='', allow_fragments=True): |
| 289 | """Parse a URL into 6 components: |
| 290 | <scheme>://<netloc>/<path>;<params>?<query>#<fragment> |
| 291 | Return a 6-tuple: (scheme, netloc, path, params, query, fragment). |
| 292 | Note that we don't break the components up in smaller bits |
| 293 | (e.g. netloc is a single string) and we don't expand % escapes.""" |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 294 | url, scheme, _coerce_result = _coerce_args(url, scheme) |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 295 | splitresult = urlsplit(url, scheme, allow_fragments) |
| 296 | scheme, netloc, url, query, fragment = splitresult |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 297 | if scheme in uses_params and ';' in url: |
| 298 | url, params = _splitparams(url) |
| 299 | else: |
| 300 | params = '' |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 301 | result = ParseResult(scheme, netloc, url, params, query, fragment) |
| 302 | return _coerce_result(result) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 303 | |
| 304 | def _splitparams(url): |
| 305 | if '/' in url: |
| 306 | i = url.find(';', url.rfind('/')) |
| 307 | if i < 0: |
| 308 | return url, '' |
| 309 | else: |
| 310 | i = url.find(';') |
| 311 | return url[:i], url[i+1:] |
| 312 | |
| 313 | def _splitnetloc(url, start=0): |
| 314 | delim = len(url) # position of end of domain part of url, default is end |
| 315 | for c in '/?#': # look for delimiters; the order is NOT important |
| 316 | wdelim = url.find(c, start) # find first of this delim |
| 317 | if wdelim >= 0: # if found |
| 318 | delim = min(delim, wdelim) # use earliest delim position |
| 319 | return url[start:delim], url[delim:] # return (domain, rest) |
| 320 | |
| 321 | def urlsplit(url, scheme='', allow_fragments=True): |
| 322 | """Parse a URL into 5 components: |
| 323 | <scheme>://<netloc>/<path>?<query>#<fragment> |
| 324 | Return a 5-tuple: (scheme, netloc, path, query, fragment). |
| 325 | Note that we don't break the components up in smaller bits |
| 326 | (e.g. netloc is a single string) and we don't expand % escapes.""" |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 327 | url, scheme, _coerce_result = _coerce_args(url, scheme) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 328 | allow_fragments = bool(allow_fragments) |
| 329 | key = url, scheme, allow_fragments, type(url), type(scheme) |
| 330 | cached = _parse_cache.get(key, None) |
| 331 | if cached: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 332 | return _coerce_result(cached) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 333 | if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth |
| 334 | clear_cache() |
| 335 | netloc = query = fragment = '' |
| 336 | i = url.find(':') |
| 337 | if i > 0: |
| 338 | if url[:i] == 'http': # optimize the common case |
| 339 | scheme = url[:i].lower() |
| 340 | url = url[i+1:] |
| 341 | if url[:2] == '//': |
| 342 | netloc, url = _splitnetloc(url, 2) |
Senthil Kumaran | 7a1e09f | 2010-04-22 12:19:46 +0000 | [diff] [blame] | 343 | if (('[' in netloc and ']' not in netloc) or |
| 344 | (']' in netloc and '[' not in netloc)): |
| 345 | raise ValueError("Invalid IPv6 URL") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 346 | if allow_fragments and '#' in url: |
| 347 | url, fragment = url.split('#', 1) |
| 348 | if '?' in url: |
| 349 | url, query = url.split('?', 1) |
| 350 | v = SplitResult(scheme, netloc, url, query, fragment) |
| 351 | _parse_cache[key] = v |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 352 | return _coerce_result(v) |
Senthil Kumaran | 397eb44 | 2011-04-15 18:20:24 +0800 | [diff] [blame] | 353 | for c in url[:i]: |
| 354 | if c not in scheme_chars: |
| 355 | break |
| 356 | else: |
Ezio Melotti | 6709b7d | 2012-05-19 17:15:19 +0300 | [diff] [blame] | 357 | # make sure "url" is not actually a port number (in which case |
| 358 | # "scheme" is really part of the path) |
| 359 | rest = url[i+1:] |
| 360 | if not rest or any(c not in '0123456789' for c in rest): |
| 361 | # not a port number |
| 362 | scheme, url = url[:i].lower(), rest |
Senthil Kumaran | 397eb44 | 2011-04-15 18:20:24 +0800 | [diff] [blame] | 363 | |
Senthil Kumaran | 6be85c5 | 2010-02-19 07:42:50 +0000 | [diff] [blame] | 364 | if url[:2] == '//': |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 365 | netloc, url = _splitnetloc(url, 2) |
Senthil Kumaran | 7a1e09f | 2010-04-22 12:19:46 +0000 | [diff] [blame] | 366 | if (('[' in netloc and ']' not in netloc) or |
| 367 | (']' in netloc and '[' not in netloc)): |
| 368 | raise ValueError("Invalid IPv6 URL") |
Senthil Kumaran | 1be320e | 2012-05-19 08:12:00 +0800 | [diff] [blame] | 369 | if allow_fragments and '#' in url: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 370 | url, fragment = url.split('#', 1) |
Senthil Kumaran | 1be320e | 2012-05-19 08:12:00 +0800 | [diff] [blame] | 371 | if '?' in url: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 372 | url, query = url.split('?', 1) |
| 373 | v = SplitResult(scheme, netloc, url, query, fragment) |
| 374 | _parse_cache[key] = v |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 375 | return _coerce_result(v) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 376 | |
| 377 | def urlunparse(components): |
| 378 | """Put a parsed URL back together again. This may result in a |
| 379 | slightly different, but equivalent URL, if the URL that was parsed |
| 380 | originally had redundant delimiters, e.g. a ? with an empty query |
| 381 | (the draft states that these are equivalent).""" |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 382 | scheme, netloc, url, params, query, fragment, _coerce_result = ( |
| 383 | _coerce_args(*components)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 384 | if params: |
| 385 | url = "%s;%s" % (url, params) |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 386 | return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment))) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 387 | |
| 388 | def urlunsplit(components): |
Senthil Kumaran | 8749a63 | 2010-06-28 14:08:00 +0000 | [diff] [blame] | 389 | """Combine the elements of a tuple as returned by urlsplit() into a |
| 390 | complete URL as a string. The data argument can be any five-item iterable. |
| 391 | This may result in a slightly different, but equivalent URL, if the URL that |
| 392 | was parsed originally had unnecessary delimiters (for example, a ? with an |
| 393 | empty query; the RFC states that these are equivalent).""" |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 394 | scheme, netloc, url, query, fragment, _coerce_result = ( |
| 395 | _coerce_args(*components)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 396 | if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'): |
| 397 | if url and url[:1] != '/': url = '/' + url |
| 398 | url = '//' + (netloc or '') + url |
| 399 | if scheme: |
| 400 | url = scheme + ':' + url |
| 401 | if query: |
| 402 | url = url + '?' + query |
| 403 | if fragment: |
| 404 | url = url + '#' + fragment |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 405 | return _coerce_result(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 406 | |
| 407 | def urljoin(base, url, allow_fragments=True): |
| 408 | """Join a base URL and a possibly relative URL to form an absolute |
| 409 | interpretation of the latter.""" |
| 410 | if not base: |
| 411 | return url |
| 412 | if not url: |
| 413 | return base |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 414 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 415 | base, url, _coerce_result = _coerce_args(base, url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 416 | bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ |
| 417 | urlparse(base, '', allow_fragments) |
| 418 | scheme, netloc, path, params, query, fragment = \ |
| 419 | urlparse(url, bscheme, allow_fragments) |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 420 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 421 | if scheme != bscheme or scheme not in uses_relative: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 422 | return _coerce_result(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 423 | if scheme in uses_netloc: |
| 424 | if netloc: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 425 | return _coerce_result(urlunparse((scheme, netloc, path, |
| 426 | params, query, fragment))) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 427 | netloc = bnetloc |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 428 | |
Senthil Kumaran | dca5b86 | 2010-12-17 04:48:45 +0000 | [diff] [blame] | 429 | if not path and not params: |
Facundo Batista | 23e3856 | 2008-08-14 16:55:14 +0000 | [diff] [blame] | 430 | path = bpath |
Senthil Kumaran | dca5b86 | 2010-12-17 04:48:45 +0000 | [diff] [blame] | 431 | params = bparams |
Facundo Batista | 23e3856 | 2008-08-14 16:55:14 +0000 | [diff] [blame] | 432 | if not query: |
| 433 | query = bquery |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 434 | return _coerce_result(urlunparse((scheme, netloc, path, |
| 435 | params, query, fragment))) |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 436 | |
| 437 | base_parts = bpath.split('/') |
| 438 | if base_parts[-1] != '': |
| 439 | # the last item is not a directory, so will not be taken into account |
| 440 | # in resolving the relative path |
| 441 | del base_parts[-1] |
| 442 | |
| 443 | # for rfc3986, ignore all base path should the first character be root. |
| 444 | if path[:1] == '/': |
| 445 | segments = path.split('/') |
| 446 | else: |
| 447 | segments = base_parts + path.split('/') |
Senthil Kumaran | a66e388 | 2014-09-22 15:49:16 +0800 | [diff] [blame] | 448 | # filter out elements that would cause redundant slashes on re-joining |
| 449 | # the resolved_path |
Berker Peksag | 20416f7 | 2015-04-16 02:31:14 +0300 | [diff] [blame] | 450 | segments[1:-1] = filter(None, segments[1:-1]) |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 451 | |
| 452 | resolved_path = [] |
| 453 | |
| 454 | for seg in segments: |
| 455 | if seg == '..': |
| 456 | try: |
| 457 | resolved_path.pop() |
| 458 | except IndexError: |
| 459 | # ignore any .. segments that would otherwise cause an IndexError |
| 460 | # when popped from resolved_path if resolving for rfc3986 |
| 461 | pass |
| 462 | elif seg == '.': |
| 463 | continue |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 464 | else: |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 465 | resolved_path.append(seg) |
| 466 | |
| 467 | if segments[-1] in ('.', '..'): |
| 468 | # do some post-processing here. if the last segment was a relative dir, |
| 469 | # then we need to append the trailing '/' |
| 470 | resolved_path.append('') |
| 471 | |
| 472 | return _coerce_result(urlunparse((scheme, netloc, '/'.join( |
Senthil Kumaran | a66e388 | 2014-09-22 15:49:16 +0800 | [diff] [blame] | 473 | resolved_path) or '/', params, query, fragment))) |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 474 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 475 | |
| 476 | def urldefrag(url): |
| 477 | """Removes any existing fragment from URL. |
| 478 | |
| 479 | Returns a tuple of the defragmented URL and the fragment. If |
| 480 | the URL contained no fragments, the second element is the |
| 481 | empty string. |
| 482 | """ |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 483 | url, _coerce_result = _coerce_args(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 484 | if '#' in url: |
| 485 | s, n, p, a, q, frag = urlparse(url) |
| 486 | defrag = urlunparse((s, n, p, a, q, '')) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 487 | else: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 488 | frag = '' |
| 489 | defrag = url |
| 490 | return _coerce_result(DefragResult(defrag, frag)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 491 | |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 492 | _hexdig = '0123456789ABCDEFabcdef' |
Victor Stinner | d6a91a7 | 2014-03-17 22:38:41 +0100 | [diff] [blame] | 493 | _hextobyte = None |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 494 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 495 | def unquote_to_bytes(string): |
| 496 | """unquote_to_bytes('abc%20def') -> b'abc def'.""" |
| 497 | # Note: strings are encoded as UTF-8. This is only an issue if it contains |
| 498 | # unescaped non-ASCII characters, which URIs should not. |
Florent Xicluna | 82a3f8a | 2010-08-14 18:30:35 +0000 | [diff] [blame] | 499 | if not string: |
| 500 | # Is it a string-like object? |
| 501 | string.split |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 502 | return b'' |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 503 | if isinstance(string, str): |
| 504 | string = string.encode('utf-8') |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 505 | bits = string.split(b'%') |
| 506 | if len(bits) == 1: |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 507 | return string |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 508 | res = [bits[0]] |
| 509 | append = res.append |
Victor Stinner | d6a91a7 | 2014-03-17 22:38:41 +0100 | [diff] [blame] | 510 | # Delay the initialization of the table to not waste memory |
| 511 | # if the function is never called |
| 512 | global _hextobyte |
| 513 | if _hextobyte is None: |
| 514 | _hextobyte = {(a + b).encode(): bytes([int(a + b, 16)]) |
| 515 | for a in _hexdig for b in _hexdig} |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 516 | for item in bits[1:]: |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 517 | try: |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 518 | append(_hextobyte[item[:2]]) |
| 519 | append(item[2:]) |
| 520 | except KeyError: |
| 521 | append(b'%') |
| 522 | append(item) |
| 523 | return b''.join(res) |
| 524 | |
| 525 | _asciire = re.compile('([\x00-\x7f]+)') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 526 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 527 | def unquote(string, encoding='utf-8', errors='replace'): |
| 528 | """Replace %xx escapes by their single-character equivalent. The optional |
| 529 | encoding and errors parameters specify how to decode percent-encoded |
| 530 | sequences into Unicode characters, as accepted by the bytes.decode() |
| 531 | method. |
| 532 | By default, percent-encoded sequences are decoded with UTF-8, and invalid |
| 533 | sequences are replaced by a placeholder character. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 534 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 535 | unquote('abc%20def') -> 'abc def'. |
| 536 | """ |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 537 | if '%' not in string: |
| 538 | string.split |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 539 | return string |
| 540 | if encoding is None: |
| 541 | encoding = 'utf-8' |
| 542 | if errors is None: |
| 543 | errors = 'replace' |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 544 | bits = _asciire.split(string) |
| 545 | res = [bits[0]] |
| 546 | append = res.append |
| 547 | for i in range(1, len(bits), 2): |
| 548 | append(unquote_to_bytes(bits[i]).decode(encoding, errors)) |
| 549 | append(bits[i + 1]) |
| 550 | return ''.join(res) |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 551 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 552 | def parse_qs(qs, keep_blank_values=False, strict_parsing=False, |
| 553 | encoding='utf-8', errors='replace'): |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 554 | """Parse a query given as a string argument. |
| 555 | |
| 556 | Arguments: |
| 557 | |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 558 | qs: percent-encoded query string to be parsed |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 559 | |
| 560 | keep_blank_values: flag indicating whether blank values in |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 561 | percent-encoded queries should be treated as blank strings. |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 562 | A true value indicates that blanks should be retained as |
| 563 | blank strings. The default false value indicates that |
| 564 | blank values are to be ignored and treated as if they were |
| 565 | not included. |
| 566 | |
| 567 | strict_parsing: flag indicating what to do with parsing errors. |
| 568 | If false (the default), errors are silently ignored. |
| 569 | If true, errors raise a ValueError exception. |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 570 | |
| 571 | encoding and errors: specify how to decode percent-encoded sequences |
| 572 | into Unicode characters, as accepted by the bytes.decode() method. |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 573 | """ |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 574 | parsed_result = {} |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 575 | pairs = parse_qsl(qs, keep_blank_values, strict_parsing, |
| 576 | encoding=encoding, errors=errors) |
| 577 | for name, value in pairs: |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 578 | if name in parsed_result: |
| 579 | parsed_result[name].append(value) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 580 | else: |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 581 | parsed_result[name] = [value] |
| 582 | return parsed_result |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 583 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 584 | def parse_qsl(qs, keep_blank_values=False, strict_parsing=False, |
| 585 | encoding='utf-8', errors='replace'): |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 586 | """Parse a query given as a string argument. |
| 587 | |
| 588 | Arguments: |
| 589 | |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 590 | qs: percent-encoded query string to be parsed |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 591 | |
| 592 | keep_blank_values: flag indicating whether blank values in |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 593 | percent-encoded queries should be treated as blank strings. A |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 594 | true value indicates that blanks should be retained as blank |
| 595 | strings. The default false value indicates that blank values |
| 596 | are to be ignored and treated as if they were not included. |
| 597 | |
| 598 | strict_parsing: flag indicating what to do with parsing errors. If |
| 599 | false (the default), errors are silently ignored. If true, |
| 600 | errors raise a ValueError exception. |
| 601 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 602 | encoding and errors: specify how to decode percent-encoded sequences |
| 603 | into Unicode characters, as accepted by the bytes.decode() method. |
| 604 | |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 605 | Returns a list, as G-d intended. |
| 606 | """ |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 607 | qs, _coerce_result = _coerce_args(qs) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 608 | pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] |
| 609 | r = [] |
| 610 | for name_value in pairs: |
| 611 | if not name_value and not strict_parsing: |
| 612 | continue |
| 613 | nv = name_value.split('=', 1) |
| 614 | if len(nv) != 2: |
| 615 | if strict_parsing: |
| 616 | raise ValueError("bad query field: %r" % (name_value,)) |
| 617 | # Handle case of a control-name with no equal sign |
| 618 | if keep_blank_values: |
| 619 | nv.append('') |
| 620 | else: |
| 621 | continue |
| 622 | if len(nv[1]) or keep_blank_values: |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 623 | name = nv[0].replace('+', ' ') |
| 624 | name = unquote(name, encoding=encoding, errors=errors) |
| 625 | name = _coerce_result(name) |
| 626 | value = nv[1].replace('+', ' ') |
| 627 | value = unquote(value, encoding=encoding, errors=errors) |
| 628 | value = _coerce_result(value) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 629 | r.append((name, value)) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 630 | return r |
| 631 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 632 | def unquote_plus(string, encoding='utf-8', errors='replace'): |
| 633 | """Like unquote(), but also replace plus signs by spaces, as required for |
| 634 | unquoting HTML form values. |
| 635 | |
| 636 | unquote_plus('%7e/abc+def') -> '~/abc def' |
| 637 | """ |
| 638 | string = string.replace('+', ' ') |
| 639 | return unquote(string, encoding, errors) |
| 640 | |
| 641 | _ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 642 | b'abcdefghijklmnopqrstuvwxyz' |
| 643 | b'0123456789' |
| 644 | b'_.-') |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 645 | _ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE) |
| 646 | _safe_quoters = {} |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 647 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 648 | class Quoter(collections.defaultdict): |
| 649 | """A mapping from bytes (in range(0,256)) to strings. |
| 650 | |
| 651 | String values are percent-encoded byte values, unless the key < 128, and |
| 652 | in the "safe" set (either the specified safe set, or default set). |
| 653 | """ |
| 654 | # Keeps a cache internally, using defaultdict, for efficiency (lookups |
| 655 | # of cached keys don't call Python code at all). |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 656 | def __init__(self, safe): |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 657 | """safe: bytes object.""" |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 658 | self.safe = _ALWAYS_SAFE.union(safe) |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 659 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 660 | def __repr__(self): |
| 661 | # Without this, will just display as a defaultdict |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 662 | return "<%s %r>" % (self.__class__.__name__, dict(self)) |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 663 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 664 | def __missing__(self, b): |
| 665 | # Handle a cache miss. Store quoted string in cache and return. |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 666 | res = chr(b) if b in self.safe else '%{:02X}'.format(b) |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 667 | self[b] = res |
| 668 | return res |
| 669 | |
| 670 | def quote(string, safe='/', encoding=None, errors=None): |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 671 | """quote('abc def') -> 'abc%20def' |
| 672 | |
| 673 | Each part of a URL, e.g. the path info, the query, etc., has a |
| 674 | different set of reserved characters that must be quoted. |
| 675 | |
| 676 | RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists |
| 677 | the following reserved characters. |
| 678 | |
| 679 | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | |
| 680 | "$" | "," |
| 681 | |
| 682 | Each of these characters is reserved in some component of a URL, |
| 683 | but not necessarily in all of them. |
| 684 | |
| 685 | By default, the quote function is intended for quoting the path |
| 686 | section of a URL. Thus, it will not encode '/'. This character |
| 687 | is reserved, but in typical usage the quote function is being |
| 688 | called on a path where the existing slash characters are used as |
| 689 | reserved characters. |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 690 | |
R David Murray | 8c4e112 | 2014-12-24 21:23:18 -0500 | [diff] [blame] | 691 | string and safe may be either str or bytes objects. encoding and errors |
| 692 | must not be specified if string is a bytes object. |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 693 | |
| 694 | The optional encoding and errors parameters specify how to deal with |
| 695 | non-ASCII characters, as accepted by the str.encode method. |
| 696 | By default, encoding='utf-8' (characters are encoded with UTF-8), and |
| 697 | errors='strict' (unsupported characters raise a UnicodeEncodeError). |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 698 | """ |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 699 | if isinstance(string, str): |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 700 | if not string: |
| 701 | return string |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 702 | if encoding is None: |
| 703 | encoding = 'utf-8' |
| 704 | if errors is None: |
| 705 | errors = 'strict' |
| 706 | string = string.encode(encoding, errors) |
| 707 | else: |
| 708 | if encoding is not None: |
| 709 | raise TypeError("quote() doesn't support 'encoding' for bytes") |
| 710 | if errors is not None: |
| 711 | raise TypeError("quote() doesn't support 'errors' for bytes") |
| 712 | return quote_from_bytes(string, safe) |
| 713 | |
| 714 | def quote_plus(string, safe='', encoding=None, errors=None): |
| 715 | """Like quote(), but also replace ' ' with '+', as required for quoting |
| 716 | HTML form values. Plus signs in the original string are escaped unless |
| 717 | they are included in safe. It also does not have safe default to '/'. |
| 718 | """ |
Jeremy Hylton | f819886 | 2009-03-26 16:55:08 +0000 | [diff] [blame] | 719 | # Check if ' ' in string, where string may either be a str or bytes. If |
| 720 | # there are no spaces, the regular quote will produce the right answer. |
| 721 | if ((isinstance(string, str) and ' ' not in string) or |
| 722 | (isinstance(string, bytes) and b' ' not in string)): |
| 723 | return quote(string, safe, encoding, errors) |
| 724 | if isinstance(safe, str): |
| 725 | space = ' ' |
| 726 | else: |
| 727 | space = b' ' |
Georg Brandl | faf4149 | 2009-05-26 18:31:11 +0000 | [diff] [blame] | 728 | string = quote(string, safe + space, encoding, errors) |
Jeremy Hylton | f819886 | 2009-03-26 16:55:08 +0000 | [diff] [blame] | 729 | return string.replace(' ', '+') |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 730 | |
| 731 | def quote_from_bytes(bs, safe='/'): |
| 732 | """Like quote(), but accepts a bytes object rather than a str, and does |
| 733 | not perform string-to-bytes encoding. It always returns an ASCII string. |
Senthil Kumaran | ffa4b2c | 2012-05-26 09:53:32 +0800 | [diff] [blame] | 734 | quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f' |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 735 | """ |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 736 | if not isinstance(bs, (bytes, bytearray)): |
| 737 | raise TypeError("quote_from_bytes() expected bytes") |
| 738 | if not bs: |
| 739 | return '' |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 740 | if isinstance(safe, str): |
| 741 | # Normalize 'safe' by converting to bytes and removing non-ASCII chars |
| 742 | safe = safe.encode('ascii', 'ignore') |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 743 | else: |
| 744 | safe = bytes([c for c in safe if c < 128]) |
| 745 | if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): |
| 746 | return bs.decode() |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 747 | try: |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 748 | quoter = _safe_quoters[safe] |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 749 | except KeyError: |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 750 | _safe_quoters[safe] = quoter = Quoter(safe).__getitem__ |
| 751 | return ''.join([quoter(char) for char in bs]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 752 | |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 753 | def urlencode(query, doseq=False, safe='', encoding=None, errors=None, |
| 754 | quote_via=quote_plus): |
Senthil Kumaran | 324ae385 | 2013-09-05 21:42:38 -0700 | [diff] [blame] | 755 | """Encode a dict or sequence of two-element tuples into a URL query string. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 756 | |
| 757 | If any values in the query arg are sequences and doseq is true, each |
| 758 | sequence element is converted to a separate parameter. |
| 759 | |
| 760 | If the query arg is a sequence of two-element tuples, the order of the |
| 761 | parameters in the output will match the order of parameters in the |
| 762 | input. |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 763 | |
Senthil Kumaran | 324ae385 | 2013-09-05 21:42:38 -0700 | [diff] [blame] | 764 | The components of a query arg may each be either a string or a bytes type. |
R David Murray | 8c4e112 | 2014-12-24 21:23:18 -0500 | [diff] [blame] | 765 | |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 766 | The safe, encoding, and errors parameters are passed down to the function |
| 767 | specified by quote_via (encoding and errors only if a component is a str). |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 768 | """ |
| 769 | |
Jeremy Hylton | a4de60a | 2009-03-26 14:49:26 +0000 | [diff] [blame] | 770 | if hasattr(query, "items"): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 771 | query = query.items() |
| 772 | else: |
Jeremy Hylton | 230feba | 2009-03-26 16:56:59 +0000 | [diff] [blame] | 773 | # It's a bother at times that strings and string-like objects are |
| 774 | # sequences. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 775 | try: |
| 776 | # non-sequence items should not work with len() |
| 777 | # non-empty strings will fail this |
| 778 | if len(query) and not isinstance(query[0], tuple): |
| 779 | raise TypeError |
Jeremy Hylton | 230feba | 2009-03-26 16:56:59 +0000 | [diff] [blame] | 780 | # Zero-length sequences of all types will get here and succeed, |
| 781 | # but that's a minor nit. Since the original implementation |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 782 | # allowed empty dicts that type of behavior probably should be |
| 783 | # preserved for consistency |
| 784 | except TypeError: |
Jeremy Hylton | a4de60a | 2009-03-26 14:49:26 +0000 | [diff] [blame] | 785 | ty, va, tb = sys.exc_info() |
| 786 | raise TypeError("not a valid non-string sequence " |
| 787 | "or mapping object").with_traceback(tb) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 788 | |
| 789 | l = [] |
| 790 | if not doseq: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 791 | for k, v in query: |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 792 | if isinstance(k, bytes): |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 793 | k = quote_via(k, safe) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 794 | else: |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 795 | k = quote_via(str(k), safe, encoding, errors) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 796 | |
| 797 | if isinstance(v, bytes): |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 798 | v = quote_via(v, safe) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 799 | else: |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 800 | v = quote_via(str(v), safe, encoding, errors) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 801 | l.append(k + '=' + v) |
| 802 | else: |
| 803 | for k, v in query: |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 804 | if isinstance(k, bytes): |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 805 | k = quote_via(k, safe) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 806 | else: |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 807 | k = quote_via(str(k), safe, encoding, errors) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 808 | |
| 809 | if isinstance(v, bytes): |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 810 | v = quote_via(v, safe) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 811 | l.append(k + '=' + v) |
| 812 | elif isinstance(v, str): |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 813 | v = quote_via(v, safe, encoding, errors) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 814 | l.append(k + '=' + v) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 815 | else: |
| 816 | try: |
Jeremy Hylton | 230feba | 2009-03-26 16:56:59 +0000 | [diff] [blame] | 817 | # Is this a sufficient test for sequence-ness? |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 818 | x = len(v) |
| 819 | except TypeError: |
| 820 | # not a sequence |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 821 | v = quote_via(str(v), safe, encoding, errors) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 822 | l.append(k + '=' + v) |
| 823 | else: |
| 824 | # loop over the sequence |
| 825 | for elt in v: |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 826 | if isinstance(elt, bytes): |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 827 | elt = quote_via(elt, safe) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 828 | else: |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame^] | 829 | elt = quote_via(str(elt), safe, encoding, errors) |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 830 | l.append(k + '=' + elt) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 831 | return '&'.join(l) |
| 832 | |
| 833 | # Utilities to parse URLs (most of these return None for missing parts): |
| 834 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
| 835 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 836 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
| 837 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 838 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
| 839 | # splitport('host:port') --> 'host', 'port' |
| 840 | # splitquery('/path?query') --> '/path', 'query' |
| 841 | # splittag('/path#tag') --> '/path', 'tag' |
| 842 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 843 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 844 | # splitvalue('attr=value') --> 'attr', 'value' |
| 845 | # urllib.parse.unquote('abc%20def') -> 'abc def' |
| 846 | # quote('abc def') -> 'abc%20def') |
| 847 | |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 848 | def to_bytes(url): |
| 849 | """to_bytes(u"URL") --> 'URL'.""" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 850 | # Most URL schemes require ASCII. If that changes, the conversion |
| 851 | # can be relaxed. |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 852 | # XXX get rid of to_bytes() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 853 | if isinstance(url, str): |
| 854 | try: |
| 855 | url = url.encode("ASCII").decode() |
| 856 | except UnicodeError: |
| 857 | raise UnicodeError("URL " + repr(url) + |
| 858 | " contains non-ASCII characters") |
| 859 | return url |
| 860 | |
| 861 | def unwrap(url): |
| 862 | """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" |
| 863 | url = str(url).strip() |
| 864 | if url[:1] == '<' and url[-1:] == '>': |
| 865 | url = url[1:-1].strip() |
| 866 | if url[:4] == 'URL:': url = url[4:].strip() |
| 867 | return url |
| 868 | |
| 869 | _typeprog = None |
| 870 | def splittype(url): |
| 871 | """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" |
| 872 | global _typeprog |
| 873 | if _typeprog is None: |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 874 | _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 875 | |
| 876 | match = _typeprog.match(url) |
| 877 | if match: |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 878 | scheme, data = match.groups() |
| 879 | return scheme.lower(), data |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 880 | return None, url |
| 881 | |
| 882 | _hostprog = None |
| 883 | def splithost(url): |
| 884 | """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" |
| 885 | global _hostprog |
| 886 | if _hostprog is None: |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 887 | _hostprog = re.compile('//([^/?]*)(.*)', re.DOTALL) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 888 | |
| 889 | match = _hostprog.match(url) |
Senthil Kumaran | c295862 | 2010-11-22 04:48:26 +0000 | [diff] [blame] | 890 | if match: |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 891 | host_port, path = match.groups() |
| 892 | if path and path[0] != '/': |
Senthil Kumaran | c295862 | 2010-11-22 04:48:26 +0000 | [diff] [blame] | 893 | path = '/' + path |
| 894 | return host_port, path |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 895 | return None, url |
| 896 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 897 | def splituser(host): |
| 898 | """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 899 | user, delim, host = host.rpartition('@') |
| 900 | return (user if delim else None), host |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 901 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 902 | def splitpasswd(user): |
| 903 | """splitpasswd('user:passwd') -> 'user', 'passwd'.""" |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 904 | user, delim, passwd = user.partition(':') |
| 905 | return user, (passwd if delim else None) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 906 | |
| 907 | # splittag('/path#tag') --> '/path', 'tag' |
| 908 | _portprog = None |
| 909 | def splitport(host): |
| 910 | """splitport('host:port') --> 'host', 'port'.""" |
| 911 | global _portprog |
| 912 | if _portprog is None: |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 913 | _portprog = re.compile('(.*):([0-9]*)$', re.DOTALL) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 914 | |
| 915 | match = _portprog.match(host) |
Serhiy Storchaka | ff97b08 | 2014-01-18 18:30:33 +0200 | [diff] [blame] | 916 | if match: |
| 917 | host, port = match.groups() |
| 918 | if port: |
| 919 | return host, port |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 920 | return host, None |
| 921 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 922 | def splitnport(host, defport=-1): |
| 923 | """Split host and port, returning numeric port. |
| 924 | Return given default port if no ':' found; defaults to -1. |
| 925 | Return numerical port if a valid number are found after ':'. |
| 926 | Return None if ':' but not a valid number.""" |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 927 | host, delim, port = host.rpartition(':') |
| 928 | if not delim: |
| 929 | host = port |
| 930 | elif port: |
| 931 | try: |
| 932 | nport = int(port) |
| 933 | except ValueError: |
| 934 | nport = None |
| 935 | return host, nport |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 936 | return host, defport |
| 937 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 938 | def splitquery(url): |
| 939 | """splitquery('/path?query') --> '/path', 'query'.""" |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 940 | path, delim, query = url.rpartition('?') |
| 941 | if delim: |
| 942 | return path, query |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 943 | return url, None |
| 944 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 945 | def splittag(url): |
| 946 | """splittag('/path#tag') --> '/path', 'tag'.""" |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 947 | path, delim, tag = url.rpartition('#') |
| 948 | if delim: |
| 949 | return path, tag |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 950 | return url, None |
| 951 | |
| 952 | def splitattr(url): |
| 953 | """splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 954 | '/path', ['attr1=value1', 'attr2=value2', ...].""" |
| 955 | words = url.split(';') |
| 956 | return words[0], words[1:] |
| 957 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 958 | def splitvalue(attr): |
| 959 | """splitvalue('attr=value') --> 'attr', 'value'.""" |
Serhiy Storchaka | 44eceb6 | 2015-03-03 20:21:35 +0200 | [diff] [blame] | 960 | attr, delim, value = attr.partition('=') |
| 961 | return attr, (value if delim else None) |