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