parse.py 35 KB

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