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