parse.py 41 KB

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