parse.py 45 KB

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