parse.py 34 KB

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