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(']') |
| 185 | _, have_port, port = port.partition(':') |
| 186 | else: |
| 187 | hostname, have_port, port = hostinfo.partition(':') |
| 188 | if not have_port: |
| 189 | port = None |
| 190 | return hostname, port |
| 191 | |
| 192 | |
| 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']') |
| 215 | _, have_port, port = port.partition(b':') |
| 216 | else: |
| 217 | hostname, have_port, port = hostinfo.partition(b':') |
| 218 | if not have_port: |
| 219 | port = None |
| 220 | return hostname, port |
| 221 | |
Jeremy 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 |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 412 | base, url, _coerce_result = _coerce_args(base, url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 413 | bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ |
| 414 | urlparse(base, '', allow_fragments) |
| 415 | scheme, netloc, path, params, query, fragment = \ |
| 416 | urlparse(url, bscheme, allow_fragments) |
| 417 | if scheme != bscheme or scheme not in uses_relative: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 418 | return _coerce_result(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 419 | if scheme in uses_netloc: |
| 420 | if netloc: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 421 | return _coerce_result(urlunparse((scheme, netloc, path, |
| 422 | params, query, fragment))) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 423 | netloc = bnetloc |
| 424 | if path[:1] == '/': |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 425 | return _coerce_result(urlunparse((scheme, netloc, path, |
| 426 | params, query, fragment))) |
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))) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 434 | segments = bpath.split('/')[:-1] + path.split('/') |
| 435 | # XXX The stuff below is bogus in various ways... |
| 436 | if segments[-1] == '.': |
| 437 | segments[-1] = '' |
| 438 | while '.' in segments: |
| 439 | segments.remove('.') |
| 440 | while 1: |
| 441 | i = 1 |
| 442 | n = len(segments) - 1 |
| 443 | while i < n: |
| 444 | if (segments[i] == '..' |
| 445 | and segments[i-1] not in ('', '..')): |
| 446 | del segments[i-1:i+1] |
| 447 | break |
| 448 | i = i+1 |
| 449 | else: |
| 450 | break |
| 451 | if segments == ['', '..']: |
| 452 | segments[-1] = '' |
| 453 | elif len(segments) >= 2 and segments[-1] == '..': |
| 454 | segments[-2:] = [''] |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 455 | return _coerce_result(urlunparse((scheme, netloc, '/'.join(segments), |
| 456 | params, query, fragment))) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 457 | |
| 458 | def urldefrag(url): |
| 459 | """Removes any existing fragment from URL. |
| 460 | |
| 461 | Returns a tuple of the defragmented URL and the fragment. If |
| 462 | the URL contained no fragments, the second element is the |
| 463 | empty string. |
| 464 | """ |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 465 | url, _coerce_result = _coerce_args(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 466 | if '#' in url: |
| 467 | s, n, p, a, q, frag = urlparse(url) |
| 468 | defrag = urlunparse((s, n, p, a, q, '')) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 469 | else: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 470 | frag = '' |
| 471 | defrag = url |
| 472 | return _coerce_result(DefragResult(defrag, frag)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 473 | |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 474 | _hexdig = '0123456789ABCDEFabcdef' |
| 475 | _hextobyte = {(a + b).encode(): bytes([int(a + b, 16)]) |
| 476 | for a in _hexdig for b in _hexdig} |
| 477 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 478 | def unquote_to_bytes(string): |
| 479 | """unquote_to_bytes('abc%20def') -> b'abc def'.""" |
| 480 | # Note: strings are encoded as UTF-8. This is only an issue if it contains |
| 481 | # unescaped non-ASCII characters, which URIs should not. |
Florent Xicluna | 82a3f8a | 2010-08-14 18:30:35 +0000 | [diff] [blame] | 482 | if not string: |
| 483 | # Is it a string-like object? |
| 484 | string.split |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 485 | return b'' |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 486 | if isinstance(string, str): |
| 487 | string = string.encode('utf-8') |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 488 | bits = string.split(b'%') |
| 489 | if len(bits) == 1: |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 490 | return string |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 491 | res = [bits[0]] |
| 492 | append = res.append |
| 493 | for item in bits[1:]: |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 494 | try: |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 495 | append(_hextobyte[item[:2]]) |
| 496 | append(item[2:]) |
| 497 | except KeyError: |
| 498 | append(b'%') |
| 499 | append(item) |
| 500 | return b''.join(res) |
| 501 | |
| 502 | _asciire = re.compile('([\x00-\x7f]+)') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 503 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 504 | def unquote(string, encoding='utf-8', errors='replace'): |
| 505 | """Replace %xx escapes by their single-character equivalent. The optional |
| 506 | encoding and errors parameters specify how to decode percent-encoded |
| 507 | sequences into Unicode characters, as accepted by the bytes.decode() |
| 508 | method. |
| 509 | By default, percent-encoded sequences are decoded with UTF-8, and invalid |
| 510 | sequences are replaced by a placeholder character. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 511 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 512 | unquote('abc%20def') -> 'abc def'. |
| 513 | """ |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 514 | if '%' not in string: |
| 515 | string.split |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 516 | return string |
| 517 | if encoding is None: |
| 518 | encoding = 'utf-8' |
| 519 | if errors is None: |
| 520 | errors = 'replace' |
Serhiy Storchaka | 8ea4616 | 2013-03-14 21:31:37 +0200 | [diff] [blame] | 521 | bits = _asciire.split(string) |
| 522 | res = [bits[0]] |
| 523 | append = res.append |
| 524 | for i in range(1, len(bits), 2): |
| 525 | append(unquote_to_bytes(bits[i]).decode(encoding, errors)) |
| 526 | append(bits[i + 1]) |
| 527 | return ''.join(res) |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 528 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 529 | def parse_qs(qs, keep_blank_values=False, strict_parsing=False, |
| 530 | encoding='utf-8', errors='replace'): |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 531 | """Parse a query given as a string argument. |
| 532 | |
| 533 | Arguments: |
| 534 | |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 535 | qs: percent-encoded query string to be parsed |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 536 | |
| 537 | keep_blank_values: flag indicating whether blank values in |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 538 | percent-encoded queries should be treated as blank strings. |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 539 | A true value indicates that blanks should be retained as |
| 540 | blank strings. The default false value indicates that |
| 541 | blank values are to be ignored and treated as if they were |
| 542 | not included. |
| 543 | |
| 544 | strict_parsing: flag indicating what to do with parsing errors. |
| 545 | If false (the default), errors are silently ignored. |
| 546 | If true, errors raise a ValueError exception. |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 547 | |
| 548 | encoding and errors: specify how to decode percent-encoded sequences |
| 549 | into Unicode characters, as accepted by the bytes.decode() method. |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 550 | """ |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 551 | parsed_result = {} |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 552 | pairs = parse_qsl(qs, keep_blank_values, strict_parsing, |
| 553 | encoding=encoding, errors=errors) |
| 554 | for name, value in pairs: |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 555 | if name in parsed_result: |
| 556 | parsed_result[name].append(value) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 557 | else: |
Senthil Kumaran | eda29f4 | 2012-06-29 11:08:20 -0700 | [diff] [blame] | 558 | parsed_result[name] = [value] |
| 559 | return parsed_result |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 560 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 561 | def parse_qsl(qs, keep_blank_values=False, strict_parsing=False, |
| 562 | encoding='utf-8', errors='replace'): |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 563 | """Parse a query given as a string argument. |
| 564 | |
| 565 | Arguments: |
| 566 | |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 567 | qs: percent-encoded query string to be parsed |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 568 | |
| 569 | keep_blank_values: flag indicating whether blank values in |
Senthil Kumaran | 30e86a4 | 2010-08-09 20:01:35 +0000 | [diff] [blame] | 570 | percent-encoded queries should be treated as blank strings. A |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 571 | true value indicates that blanks should be retained as blank |
| 572 | strings. The default false value indicates that blank values |
| 573 | are to be ignored and treated as if they were not included. |
| 574 | |
| 575 | strict_parsing: flag indicating what to do with parsing errors. If |
| 576 | false (the default), errors are silently ignored. If true, |
| 577 | errors raise a ValueError exception. |
| 578 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 579 | encoding and errors: specify how to decode percent-encoded sequences |
| 580 | into Unicode characters, as accepted by the bytes.decode() method. |
| 581 | |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 582 | Returns a list, as G-d intended. |
| 583 | """ |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 584 | qs, _coerce_result = _coerce_args(qs) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 585 | pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] |
| 586 | r = [] |
| 587 | for name_value in pairs: |
| 588 | if not name_value and not strict_parsing: |
| 589 | continue |
| 590 | nv = name_value.split('=', 1) |
| 591 | if len(nv) != 2: |
| 592 | if strict_parsing: |
| 593 | raise ValueError("bad query field: %r" % (name_value,)) |
| 594 | # Handle case of a control-name with no equal sign |
| 595 | if keep_blank_values: |
| 596 | nv.append('') |
| 597 | else: |
| 598 | continue |
| 599 | if len(nv[1]) or keep_blank_values: |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 600 | name = nv[0].replace('+', ' ') |
| 601 | name = unquote(name, encoding=encoding, errors=errors) |
| 602 | name = _coerce_result(name) |
| 603 | value = nv[1].replace('+', ' ') |
| 604 | value = unquote(value, encoding=encoding, errors=errors) |
| 605 | value = _coerce_result(value) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 606 | r.append((name, value)) |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 607 | return r |
| 608 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 609 | def unquote_plus(string, encoding='utf-8', errors='replace'): |
| 610 | """Like unquote(), but also replace plus signs by spaces, as required for |
| 611 | unquoting HTML form values. |
| 612 | |
| 613 | unquote_plus('%7e/abc+def') -> '~/abc def' |
| 614 | """ |
| 615 | string = string.replace('+', ' ') |
| 616 | return unquote(string, encoding, errors) |
| 617 | |
| 618 | _ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 619 | b'abcdefghijklmnopqrstuvwxyz' |
| 620 | b'0123456789' |
| 621 | b'_.-') |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 622 | _ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE) |
| 623 | _safe_quoters = {} |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 624 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 625 | class Quoter(collections.defaultdict): |
| 626 | """A mapping from bytes (in range(0,256)) to strings. |
| 627 | |
| 628 | String values are percent-encoded byte values, unless the key < 128, and |
| 629 | in the "safe" set (either the specified safe set, or default set). |
| 630 | """ |
| 631 | # Keeps a cache internally, using defaultdict, for efficiency (lookups |
| 632 | # of cached keys don't call Python code at all). |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 633 | def __init__(self, safe): |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 634 | """safe: bytes object.""" |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 635 | self.safe = _ALWAYS_SAFE.union(safe) |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 636 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 637 | def __repr__(self): |
| 638 | # Without this, will just display as a defaultdict |
| 639 | return "<Quoter %r>" % dict(self) |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 640 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 641 | def __missing__(self, b): |
| 642 | # Handle a cache miss. Store quoted string in cache and return. |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 643 | 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] | 644 | self[b] = res |
| 645 | return res |
| 646 | |
| 647 | def quote(string, safe='/', encoding=None, errors=None): |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 648 | """quote('abc def') -> 'abc%20def' |
| 649 | |
| 650 | Each part of a URL, e.g. the path info, the query, etc., has a |
| 651 | different set of reserved characters that must be quoted. |
| 652 | |
| 653 | RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists |
| 654 | the following reserved characters. |
| 655 | |
| 656 | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | |
| 657 | "$" | "," |
| 658 | |
| 659 | Each of these characters is reserved in some component of a URL, |
| 660 | but not necessarily in all of them. |
| 661 | |
| 662 | By default, the quote function is intended for quoting the path |
| 663 | section of a URL. Thus, it will not encode '/'. This character |
| 664 | is reserved, but in typical usage the quote function is being |
| 665 | called on a path where the existing slash characters are used as |
| 666 | reserved characters. |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 667 | |
| 668 | string and safe may be either str or bytes objects. encoding must |
| 669 | not be specified if string is a str. |
| 670 | |
| 671 | The optional encoding and errors parameters specify how to deal with |
| 672 | non-ASCII characters, as accepted by the str.encode method. |
| 673 | By default, encoding='utf-8' (characters are encoded with UTF-8), and |
| 674 | errors='strict' (unsupported characters raise a UnicodeEncodeError). |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 675 | """ |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 676 | if isinstance(string, str): |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 677 | if not string: |
| 678 | return string |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 679 | if encoding is None: |
| 680 | encoding = 'utf-8' |
| 681 | if errors is None: |
| 682 | errors = 'strict' |
| 683 | string = string.encode(encoding, errors) |
| 684 | else: |
| 685 | if encoding is not None: |
| 686 | raise TypeError("quote() doesn't support 'encoding' for bytes") |
| 687 | if errors is not None: |
| 688 | raise TypeError("quote() doesn't support 'errors' for bytes") |
| 689 | return quote_from_bytes(string, safe) |
| 690 | |
| 691 | def quote_plus(string, safe='', encoding=None, errors=None): |
| 692 | """Like quote(), but also replace ' ' with '+', as required for quoting |
| 693 | HTML form values. Plus signs in the original string are escaped unless |
| 694 | they are included in safe. It also does not have safe default to '/'. |
| 695 | """ |
Jeremy Hylton | f819886 | 2009-03-26 16:55:08 +0000 | [diff] [blame] | 696 | # Check if ' ' in string, where string may either be a str or bytes. If |
| 697 | # there are no spaces, the regular quote will produce the right answer. |
| 698 | if ((isinstance(string, str) and ' ' not in string) or |
| 699 | (isinstance(string, bytes) and b' ' not in string)): |
| 700 | return quote(string, safe, encoding, errors) |
| 701 | if isinstance(safe, str): |
| 702 | space = ' ' |
| 703 | else: |
| 704 | space = b' ' |
Georg Brandl | faf4149 | 2009-05-26 18:31:11 +0000 | [diff] [blame] | 705 | string = quote(string, safe + space, encoding, errors) |
Jeremy Hylton | f819886 | 2009-03-26 16:55:08 +0000 | [diff] [blame] | 706 | return string.replace(' ', '+') |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 707 | |
| 708 | def quote_from_bytes(bs, safe='/'): |
| 709 | """Like quote(), but accepts a bytes object rather than a str, and does |
| 710 | not perform string-to-bytes encoding. It always returns an ASCII string. |
Senthil Kumaran | ffa4b2c | 2012-05-26 09:53:32 +0800 | [diff] [blame] | 711 | quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f' |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 712 | """ |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 713 | if not isinstance(bs, (bytes, bytearray)): |
| 714 | raise TypeError("quote_from_bytes() expected bytes") |
| 715 | if not bs: |
| 716 | return '' |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 717 | if isinstance(safe, str): |
| 718 | # Normalize 'safe' by converting to bytes and removing non-ASCII chars |
| 719 | safe = safe.encode('ascii', 'ignore') |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 720 | else: |
| 721 | safe = bytes([c for c in safe if c < 128]) |
| 722 | if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): |
| 723 | return bs.decode() |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 724 | try: |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 725 | quoter = _safe_quoters[safe] |
Guido van Rossum | df9f1ec | 2008-08-06 19:31:34 +0000 | [diff] [blame] | 726 | except KeyError: |
Florent Xicluna | c7b8e86 | 2010-05-17 17:33:07 +0000 | [diff] [blame] | 727 | _safe_quoters[safe] = quoter = Quoter(safe).__getitem__ |
| 728 | return ''.join([quoter(char) for char in bs]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 729 | |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 730 | def urlencode(query, doseq=False, safe='', encoding=None, errors=None): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 731 | """Encode a sequence of two-element tuples or dictionary into a URL query string. |
| 732 | |
| 733 | If any values in the query arg are sequences and doseq is true, each |
| 734 | sequence element is converted to a separate parameter. |
| 735 | |
| 736 | If the query arg is a sequence of two-element tuples, the order of the |
| 737 | parameters in the output will match the order of parameters in the |
| 738 | input. |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 739 | |
| 740 | The query arg may be either a string or a bytes type. When query arg is a |
| 741 | string, the safe, encoding and error parameters are sent the quote_plus for |
| 742 | encoding. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 743 | """ |
| 744 | |
Jeremy Hylton | a4de60a | 2009-03-26 14:49:26 +0000 | [diff] [blame] | 745 | if hasattr(query, "items"): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 746 | query = query.items() |
| 747 | else: |
Jeremy Hylton | 230feba | 2009-03-26 16:56:59 +0000 | [diff] [blame] | 748 | # It's a bother at times that strings and string-like objects are |
| 749 | # sequences. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 750 | try: |
| 751 | # non-sequence items should not work with len() |
| 752 | # non-empty strings will fail this |
| 753 | if len(query) and not isinstance(query[0], tuple): |
| 754 | raise TypeError |
Jeremy Hylton | 230feba | 2009-03-26 16:56:59 +0000 | [diff] [blame] | 755 | # Zero-length sequences of all types will get here and succeed, |
| 756 | # but that's a minor nit. Since the original implementation |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 757 | # allowed empty dicts that type of behavior probably should be |
| 758 | # preserved for consistency |
| 759 | except TypeError: |
Jeremy Hylton | a4de60a | 2009-03-26 14:49:26 +0000 | [diff] [blame] | 760 | ty, va, tb = sys.exc_info() |
| 761 | raise TypeError("not a valid non-string sequence " |
| 762 | "or mapping object").with_traceback(tb) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 763 | |
| 764 | l = [] |
| 765 | if not doseq: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 766 | for k, v in query: |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 767 | if isinstance(k, bytes): |
| 768 | k = quote_plus(k, safe) |
| 769 | else: |
| 770 | k = quote_plus(str(k), safe, encoding, errors) |
| 771 | |
| 772 | if isinstance(v, bytes): |
| 773 | v = quote_plus(v, safe) |
| 774 | else: |
| 775 | v = quote_plus(str(v), safe, encoding, errors) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 776 | l.append(k + '=' + v) |
| 777 | else: |
| 778 | for k, v in query: |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 779 | if isinstance(k, bytes): |
| 780 | k = quote_plus(k, safe) |
| 781 | else: |
| 782 | k = quote_plus(str(k), safe, encoding, errors) |
| 783 | |
| 784 | if isinstance(v, bytes): |
| 785 | v = quote_plus(v, safe) |
| 786 | l.append(k + '=' + v) |
| 787 | elif isinstance(v, str): |
| 788 | v = quote_plus(v, safe, encoding, errors) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 789 | l.append(k + '=' + v) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 790 | else: |
| 791 | try: |
Jeremy Hylton | 230feba | 2009-03-26 16:56:59 +0000 | [diff] [blame] | 792 | # Is this a sufficient test for sequence-ness? |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 793 | x = len(v) |
| 794 | except TypeError: |
| 795 | # not a sequence |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 796 | v = quote_plus(str(v), safe, encoding, errors) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 797 | l.append(k + '=' + v) |
| 798 | else: |
| 799 | # loop over the sequence |
| 800 | for elt in v: |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 801 | if isinstance(elt, bytes): |
| 802 | elt = quote_plus(elt, safe) |
| 803 | else: |
| 804 | elt = quote_plus(str(elt), safe, encoding, errors) |
| 805 | l.append(k + '=' + elt) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 806 | return '&'.join(l) |
| 807 | |
| 808 | # Utilities to parse URLs (most of these return None for missing parts): |
| 809 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
| 810 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 811 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
| 812 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 813 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
| 814 | # splitport('host:port') --> 'host', 'port' |
| 815 | # splitquery('/path?query') --> '/path', 'query' |
| 816 | # splittag('/path#tag') --> '/path', 'tag' |
| 817 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 818 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 819 | # splitvalue('attr=value') --> 'attr', 'value' |
| 820 | # urllib.parse.unquote('abc%20def') -> 'abc def' |
| 821 | # quote('abc def') -> 'abc%20def') |
| 822 | |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 823 | def to_bytes(url): |
| 824 | """to_bytes(u"URL") --> 'URL'.""" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 825 | # Most URL schemes require ASCII. If that changes, the conversion |
| 826 | # can be relaxed. |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 827 | # XXX get rid of to_bytes() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 828 | if isinstance(url, str): |
| 829 | try: |
| 830 | url = url.encode("ASCII").decode() |
| 831 | except UnicodeError: |
| 832 | raise UnicodeError("URL " + repr(url) + |
| 833 | " contains non-ASCII characters") |
| 834 | return url |
| 835 | |
| 836 | def unwrap(url): |
| 837 | """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" |
| 838 | url = str(url).strip() |
| 839 | if url[:1] == '<' and url[-1:] == '>': |
| 840 | url = url[1:-1].strip() |
| 841 | if url[:4] == 'URL:': url = url[4:].strip() |
| 842 | return url |
| 843 | |
| 844 | _typeprog = None |
| 845 | def splittype(url): |
| 846 | """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" |
| 847 | global _typeprog |
| 848 | if _typeprog is None: |
| 849 | import re |
| 850 | _typeprog = re.compile('^([^/:]+):') |
| 851 | |
| 852 | match = _typeprog.match(url) |
| 853 | if match: |
| 854 | scheme = match.group(1) |
| 855 | return scheme.lower(), url[len(scheme) + 1:] |
| 856 | return None, url |
| 857 | |
| 858 | _hostprog = None |
| 859 | def splithost(url): |
| 860 | """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" |
| 861 | global _hostprog |
| 862 | if _hostprog is None: |
| 863 | import re |
| 864 | _hostprog = re.compile('^//([^/?]*)(.*)$') |
| 865 | |
| 866 | match = _hostprog.match(url) |
Senthil Kumaran | c295862 | 2010-11-22 04:48:26 +0000 | [diff] [blame] | 867 | if match: |
| 868 | host_port = match.group(1) |
| 869 | path = match.group(2) |
| 870 | if path and not path.startswith('/'): |
| 871 | path = '/' + path |
| 872 | return host_port, path |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 873 | return None, url |
| 874 | |
| 875 | _userprog = None |
| 876 | def splituser(host): |
| 877 | """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" |
| 878 | global _userprog |
| 879 | if _userprog is None: |
| 880 | import re |
| 881 | _userprog = re.compile('^(.*)@(.*)$') |
| 882 | |
| 883 | match = _userprog.match(host) |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 884 | if match: return match.group(1, 2) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 885 | return None, host |
| 886 | |
| 887 | _passwdprog = None |
| 888 | def splitpasswd(user): |
| 889 | """splitpasswd('user:passwd') -> 'user', 'passwd'.""" |
| 890 | global _passwdprog |
| 891 | if _passwdprog is None: |
| 892 | import re |
Senthil Kumaran | eaaec27 | 2009-03-30 21:54:41 +0000 | [diff] [blame] | 893 | _passwdprog = re.compile('^([^:]*):(.*)$',re.S) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 894 | |
| 895 | match = _passwdprog.match(user) |
| 896 | if match: return match.group(1, 2) |
| 897 | return user, None |
| 898 | |
| 899 | # splittag('/path#tag') --> '/path', 'tag' |
| 900 | _portprog = None |
| 901 | def splitport(host): |
| 902 | """splitport('host:port') --> 'host', 'port'.""" |
| 903 | global _portprog |
| 904 | if _portprog is None: |
| 905 | import re |
| 906 | _portprog = re.compile('^(.*):([0-9]+)$') |
| 907 | |
| 908 | match = _portprog.match(host) |
| 909 | if match: return match.group(1, 2) |
| 910 | return host, None |
| 911 | |
| 912 | _nportprog = None |
| 913 | def splitnport(host, defport=-1): |
| 914 | """Split host and port, returning numeric port. |
| 915 | Return given default port if no ':' found; defaults to -1. |
| 916 | Return numerical port if a valid number are found after ':'. |
| 917 | Return None if ':' but not a valid number.""" |
| 918 | global _nportprog |
| 919 | if _nportprog is None: |
| 920 | import re |
| 921 | _nportprog = re.compile('^(.*):(.*)$') |
| 922 | |
| 923 | match = _nportprog.match(host) |
| 924 | if match: |
| 925 | host, port = match.group(1, 2) |
| 926 | try: |
| 927 | if not port: raise ValueError("no digits") |
| 928 | nport = int(port) |
| 929 | except ValueError: |
| 930 | nport = None |
| 931 | return host, nport |
| 932 | return host, defport |
| 933 | |
| 934 | _queryprog = None |
| 935 | def splitquery(url): |
| 936 | """splitquery('/path?query') --> '/path', 'query'.""" |
| 937 | global _queryprog |
| 938 | if _queryprog is None: |
| 939 | import re |
| 940 | _queryprog = re.compile('^(.*)\?([^?]*)$') |
| 941 | |
| 942 | match = _queryprog.match(url) |
| 943 | if match: return match.group(1, 2) |
| 944 | return url, None |
| 945 | |
| 946 | _tagprog = None |
| 947 | def splittag(url): |
| 948 | """splittag('/path#tag') --> '/path', 'tag'.""" |
| 949 | global _tagprog |
| 950 | if _tagprog is None: |
| 951 | import re |
| 952 | _tagprog = re.compile('^(.*)#([^#]*)$') |
| 953 | |
| 954 | match = _tagprog.match(url) |
| 955 | if match: return match.group(1, 2) |
| 956 | return url, None |
| 957 | |
| 958 | def splitattr(url): |
| 959 | """splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 960 | '/path', ['attr1=value1', 'attr2=value2', ...].""" |
| 961 | words = url.split(';') |
| 962 | return words[0], words[1:] |
| 963 | |
| 964 | _valueprog = None |
| 965 | def splitvalue(attr): |
| 966 | """splitvalue('attr=value') --> 'attr', 'value'.""" |
| 967 | global _valueprog |
| 968 | if _valueprog is None: |
| 969 | import re |
| 970 | _valueprog = re.compile('^([^=]*)=(.*)$') |
| 971 | |
| 972 | match = _valueprog.match(attr) |
| 973 | if match: return match.group(1, 2) |
| 974 | return attr, None |