logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

parse.py (42278B)


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