parse.py 42 KB

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