parse.py 38 KB

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