parse.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. # Valid bracketed hosts are defined in
  355. # https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/
  356. def _check_bracketed_host(hostname):
  357. if hostname.startswith('v'):
  358. if not re.match(r"\Av[a-fA-F0-9]+\..+\Z", hostname):
  359. raise ValueError(f"IPvFuture address is invalid")
  360. else:
  361. ip = ipaddress.ip_address(hostname) # Throws Value Error if not IPv6 or IPv4
  362. if isinstance(ip, ipaddress.IPv4Address):
  363. raise ValueError(f"An IPv4 address cannot be in brackets")
  364. # typed=True avoids BytesWarnings being emitted during cache key
  365. # comparison since this API supports both bytes and str input.
  366. @functools.lru_cache(typed=True)
  367. def urlsplit(url, scheme='', allow_fragments=True):
  368. """Parse a URL into 5 components:
  369. <scheme>://<netloc>/<path>?<query>#<fragment>
  370. The result is a named 5-tuple with fields corresponding to the
  371. above. It is either a SplitResult or SplitResultBytes object,
  372. depending on the type of the url parameter.
  373. The username, password, hostname, and port sub-components of netloc
  374. can also be accessed as attributes of the returned object.
  375. The scheme argument provides the default value of the scheme
  376. component when no scheme is found in url.
  377. If allow_fragments is False, no attempt is made to separate the
  378. fragment component from the previous component, which can be either
  379. path or query.
  380. Note that % escapes are not expanded.
  381. """
  382. url, scheme, _coerce_result = _coerce_args(url, scheme)
  383. # Only lstrip url as some applications rely on preserving trailing space.
  384. # (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both)
  385. url = url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)
  386. scheme = scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)
  387. for b in _UNSAFE_URL_BYTES_TO_REMOVE:
  388. url = url.replace(b, "")
  389. scheme = scheme.replace(b, "")
  390. allow_fragments = bool(allow_fragments)
  391. netloc = query = fragment = ''
  392. i = url.find(':')
  393. if i > 0 and url[0].isascii() and url[0].isalpha():
  394. for c in url[:i]:
  395. if c not in scheme_chars:
  396. break
  397. else:
  398. scheme, url = url[:i].lower(), url[i+1:]
  399. if url[:2] == '//':
  400. netloc, url = _splitnetloc(url, 2)
  401. if (('[' in netloc and ']' not in netloc) or
  402. (']' in netloc and '[' not in netloc)):
  403. raise ValueError("Invalid IPv6 URL")
  404. if '[' in netloc and ']' in netloc:
  405. bracketed_host = netloc.partition('[')[2].partition(']')[0]
  406. _check_bracketed_host(bracketed_host)
  407. if allow_fragments and '#' in url:
  408. url, fragment = url.split('#', 1)
  409. if '?' in url:
  410. url, query = url.split('?', 1)
  411. _checknetloc(netloc)
  412. v = SplitResult(scheme, netloc, url, query, fragment)
  413. return _coerce_result(v)
  414. def urlunparse(components):
  415. """Put a parsed URL back together again. This may result in a
  416. slightly different, but equivalent URL, if the URL that was parsed
  417. originally had redundant delimiters, e.g. a ? with an empty query
  418. (the draft states that these are equivalent)."""
  419. scheme, netloc, url, params, query, fragment, _coerce_result = (
  420. _coerce_args(*components))
  421. if params:
  422. url = "%s;%s" % (url, params)
  423. return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
  424. def urlunsplit(components):
  425. """Combine the elements of a tuple as returned by urlsplit() into a
  426. complete URL as a string. The data argument can be any five-item iterable.
  427. This may result in a slightly different, but equivalent URL, if the URL that
  428. was parsed originally had unnecessary delimiters (for example, a ? with an
  429. empty query; the RFC states that these are equivalent)."""
  430. scheme, netloc, url, query, fragment, _coerce_result = (
  431. _coerce_args(*components))
  432. if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
  433. if url and url[:1] != '/': url = '/' + url
  434. url = '//' + (netloc or '') + url
  435. if scheme:
  436. url = scheme + ':' + url
  437. if query:
  438. url = url + '?' + query
  439. if fragment:
  440. url = url + '#' + fragment
  441. return _coerce_result(url)
  442. def urljoin(base, url, allow_fragments=True):
  443. """Join a base URL and a possibly relative URL to form an absolute
  444. interpretation of the latter."""
  445. if not base:
  446. return url
  447. if not url:
  448. return base
  449. base, url, _coerce_result = _coerce_args(base, url)
  450. bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
  451. urlparse(base, '', allow_fragments)
  452. scheme, netloc, path, params, query, fragment = \
  453. urlparse(url, bscheme, allow_fragments)
  454. if scheme != bscheme or scheme not in uses_relative:
  455. return _coerce_result(url)
  456. if scheme in uses_netloc:
  457. if netloc:
  458. return _coerce_result(urlunparse((scheme, netloc, path,
  459. params, query, fragment)))
  460. netloc = bnetloc
  461. if not path and not params:
  462. path = bpath
  463. params = bparams
  464. if not query:
  465. query = bquery
  466. return _coerce_result(urlunparse((scheme, netloc, path,
  467. params, query, fragment)))
  468. base_parts = bpath.split('/')
  469. if base_parts[-1] != '':
  470. # the last item is not a directory, so will not be taken into account
  471. # in resolving the relative path
  472. del base_parts[-1]
  473. # for rfc3986, ignore all base path should the first character be root.
  474. if path[:1] == '/':
  475. segments = path.split('/')
  476. else:
  477. segments = base_parts + path.split('/')
  478. # filter out elements that would cause redundant slashes on re-joining
  479. # the resolved_path
  480. segments[1:-1] = filter(None, segments[1:-1])
  481. resolved_path = []
  482. for seg in segments:
  483. if seg == '..':
  484. try:
  485. resolved_path.pop()
  486. except IndexError:
  487. # ignore any .. segments that would otherwise cause an IndexError
  488. # when popped from resolved_path if resolving for rfc3986
  489. pass
  490. elif seg == '.':
  491. continue
  492. else:
  493. resolved_path.append(seg)
  494. if segments[-1] in ('.', '..'):
  495. # do some post-processing here. if the last segment was a relative dir,
  496. # then we need to append the trailing '/'
  497. resolved_path.append('')
  498. return _coerce_result(urlunparse((scheme, netloc, '/'.join(
  499. resolved_path) or '/', params, query, fragment)))
  500. def urldefrag(url):
  501. """Removes any existing fragment from URL.
  502. Returns a tuple of the defragmented URL and the fragment. If
  503. the URL contained no fragments, the second element is the
  504. empty string.
  505. """
  506. url, _coerce_result = _coerce_args(url)
  507. if '#' in url:
  508. s, n, p, a, q, frag = urlparse(url)
  509. defrag = urlunparse((s, n, p, a, q, ''))
  510. else:
  511. frag = ''
  512. defrag = url
  513. return _coerce_result(DefragResult(defrag, frag))
  514. _hexdig = '0123456789ABCDEFabcdef'
  515. _hextobyte = None
  516. def unquote_to_bytes(string):
  517. """unquote_to_bytes('abc%20def') -> b'abc def'."""
  518. return bytes(_unquote_impl(string))
  519. def _unquote_impl(string: bytes | bytearray | str) -> bytes | bytearray:
  520. # Note: strings are encoded as UTF-8. This is only an issue if it contains
  521. # unescaped non-ASCII characters, which URIs should not.
  522. if not string:
  523. # Is it a string-like object?
  524. string.split
  525. return b''
  526. if isinstance(string, str):
  527. string = string.encode('utf-8')
  528. bits = string.split(b'%')
  529. if len(bits) == 1:
  530. return string
  531. res = bytearray(bits[0])
  532. append = res.extend
  533. # Delay the initialization of the table to not waste memory
  534. # if the function is never called
  535. global _hextobyte
  536. if _hextobyte is None:
  537. _hextobyte = {(a + b).encode(): bytes.fromhex(a + b)
  538. for a in _hexdig for b in _hexdig}
  539. for item in bits[1:]:
  540. try:
  541. append(_hextobyte[item[:2]])
  542. append(item[2:])
  543. except KeyError:
  544. append(b'%')
  545. append(item)
  546. return res
  547. _asciire = re.compile('([\x00-\x7f]+)')
  548. def _generate_unquoted_parts(string, encoding, errors):
  549. previous_match_end = 0
  550. for ascii_match in _asciire.finditer(string):
  551. start, end = ascii_match.span()
  552. yield string[previous_match_end:start] # Non-ASCII
  553. # The ascii_match[1] group == string[start:end].
  554. yield _unquote_impl(ascii_match[1]).decode(encoding, errors)
  555. previous_match_end = end
  556. yield string[previous_match_end:] # Non-ASCII tail
  557. def unquote(string, encoding='utf-8', errors='replace'):
  558. """Replace %xx escapes by their single-character equivalent. The optional
  559. encoding and errors parameters specify how to decode percent-encoded
  560. sequences into Unicode characters, as accepted by the bytes.decode()
  561. method.
  562. By default, percent-encoded sequences are decoded with UTF-8, and invalid
  563. sequences are replaced by a placeholder character.
  564. unquote('abc%20def') -> 'abc def'.
  565. """
  566. if isinstance(string, bytes):
  567. return _unquote_impl(string).decode(encoding, errors)
  568. if '%' not in string:
  569. # Is it a string-like object?
  570. string.split
  571. return string
  572. if encoding is None:
  573. encoding = 'utf-8'
  574. if errors is None:
  575. errors = 'replace'
  576. return ''.join(_generate_unquoted_parts(string, encoding, errors))
  577. def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  578. encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):
  579. """Parse a query given as a string argument.
  580. Arguments:
  581. qs: percent-encoded query string to be parsed
  582. keep_blank_values: flag indicating whether blank values in
  583. percent-encoded queries should be treated as blank strings.
  584. A true value indicates that blanks should be retained as
  585. blank strings. The default false value indicates that
  586. blank values are to be ignored and treated as if they were
  587. not included.
  588. strict_parsing: flag indicating what to do with parsing errors.
  589. If false (the default), errors are silently ignored.
  590. If true, errors raise a ValueError exception.
  591. encoding and errors: specify how to decode percent-encoded sequences
  592. into Unicode characters, as accepted by the bytes.decode() method.
  593. max_num_fields: int. If set, then throws a ValueError if there
  594. are more than n fields read by parse_qsl().
  595. separator: str. The symbol to use for separating the query arguments.
  596. Defaults to &.
  597. Returns a dictionary.
  598. """
  599. parsed_result = {}
  600. pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
  601. encoding=encoding, errors=errors,
  602. max_num_fields=max_num_fields, separator=separator)
  603. for name, value in pairs:
  604. if name in parsed_result:
  605. parsed_result[name].append(value)
  606. else:
  607. parsed_result[name] = [value]
  608. return parsed_result
  609. def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  610. encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):
  611. """Parse a query given as a string argument.
  612. Arguments:
  613. qs: percent-encoded query string to be parsed
  614. keep_blank_values: flag indicating whether blank values in
  615. percent-encoded queries should be treated as blank strings.
  616. A true value indicates that blanks should be retained as blank
  617. strings. The default false value indicates that blank values
  618. are to be ignored and treated as if they were not included.
  619. strict_parsing: flag indicating what to do with parsing errors. If
  620. false (the default), errors are silently ignored. If true,
  621. errors raise a ValueError exception.
  622. encoding and errors: specify how to decode percent-encoded sequences
  623. into Unicode characters, as accepted by the bytes.decode() method.
  624. max_num_fields: int. If set, then throws a ValueError
  625. if there are more than n fields read by parse_qsl().
  626. separator: str. The symbol to use for separating the query arguments.
  627. Defaults to &.
  628. Returns a list, as G-d intended.
  629. """
  630. qs, _coerce_result = _coerce_args(qs)
  631. separator, _ = _coerce_args(separator)
  632. if not separator or (not isinstance(separator, (str, bytes))):
  633. raise ValueError("Separator must be of type string or bytes.")
  634. # If max_num_fields is defined then check that the number of fields
  635. # is less than max_num_fields. This prevents a memory exhaustion DOS
  636. # attack via post bodies with many fields.
  637. if max_num_fields is not None:
  638. num_fields = 1 + qs.count(separator) if qs else 0
  639. if max_num_fields < num_fields:
  640. raise ValueError('Max number of fields exceeded')
  641. r = []
  642. query_args = qs.split(separator) if qs else []
  643. for name_value in query_args:
  644. if not name_value and not strict_parsing:
  645. continue
  646. nv = name_value.split('=', 1)
  647. if len(nv) != 2:
  648. if strict_parsing:
  649. raise ValueError("bad query field: %r" % (name_value,))
  650. # Handle case of a control-name with no equal sign
  651. if keep_blank_values:
  652. nv.append('')
  653. else:
  654. continue
  655. if len(nv[1]) or keep_blank_values:
  656. name = nv[0].replace('+', ' ')
  657. name = unquote(name, encoding=encoding, errors=errors)
  658. name = _coerce_result(name)
  659. value = nv[1].replace('+', ' ')
  660. value = unquote(value, encoding=encoding, errors=errors)
  661. value = _coerce_result(value)
  662. r.append((name, value))
  663. return r
  664. def unquote_plus(string, encoding='utf-8', errors='replace'):
  665. """Like unquote(), but also replace plus signs by spaces, as required for
  666. unquoting HTML form values.
  667. unquote_plus('%7e/abc+def') -> '~/abc def'
  668. """
  669. string = string.replace('+', ' ')
  670. return unquote(string, encoding, errors)
  671. _ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  672. b'abcdefghijklmnopqrstuvwxyz'
  673. b'0123456789'
  674. b'_.-~')
  675. _ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
  676. def __getattr__(name):
  677. if name == 'Quoter':
  678. warnings.warn('Deprecated in 3.11. '
  679. 'urllib.parse.Quoter will be removed in Python 3.14. '
  680. 'It was not intended to be a public API.',
  681. DeprecationWarning, stacklevel=2)
  682. return _Quoter
  683. raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
  684. class _Quoter(dict):
  685. """A mapping from bytes numbers (in range(0,256)) to strings.
  686. String values are percent-encoded byte values, unless the key < 128, and
  687. in either of the specified safe set, or the always safe set.
  688. """
  689. # Keeps a cache internally, via __missing__, for efficiency (lookups
  690. # of cached keys don't call Python code at all).
  691. def __init__(self, safe):
  692. """safe: bytes object."""
  693. self.safe = _ALWAYS_SAFE.union(safe)
  694. def __repr__(self):
  695. return f"<Quoter {dict(self)!r}>"
  696. def __missing__(self, b):
  697. # Handle a cache miss. Store quoted string in cache and return.
  698. res = chr(b) if b in self.safe else '%{:02X}'.format(b)
  699. self[b] = res
  700. return res
  701. def quote(string, safe='/', encoding=None, errors=None):
  702. """quote('abc def') -> 'abc%20def'
  703. Each part of a URL, e.g. the path info, the query, etc., has a
  704. different set of reserved characters that must be quoted. The
  705. quote function offers a cautious (not minimal) way to quote a
  706. string for most of these parts.
  707. RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists
  708. the following (un)reserved characters.
  709. unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  710. reserved = gen-delims / sub-delims
  711. gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
  712. sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  713. / "*" / "+" / "," / ";" / "="
  714. Each of the reserved characters is reserved in some component of a URL,
  715. but not necessarily in all of them.
  716. The quote function %-escapes all characters that are neither in the
  717. unreserved chars ("always safe") nor the additional chars set via the
  718. safe arg.
  719. The default for the safe arg is '/'. The character is reserved, but in
  720. typical usage the quote function is being called on a path where the
  721. existing slash characters are to be preserved.
  722. Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
  723. Now, "~" is included in the set of unreserved characters.
  724. string and safe may be either str or bytes objects. encoding and errors
  725. must not be specified if string is a bytes object.
  726. The optional encoding and errors parameters specify how to deal with
  727. non-ASCII characters, as accepted by the str.encode method.
  728. By default, encoding='utf-8' (characters are encoded with UTF-8), and
  729. errors='strict' (unsupported characters raise a UnicodeEncodeError).
  730. """
  731. if isinstance(string, str):
  732. if not string:
  733. return string
  734. if encoding is None:
  735. encoding = 'utf-8'
  736. if errors is None:
  737. errors = 'strict'
  738. string = string.encode(encoding, errors)
  739. else:
  740. if encoding is not None:
  741. raise TypeError("quote() doesn't support 'encoding' for bytes")
  742. if errors is not None:
  743. raise TypeError("quote() doesn't support 'errors' for bytes")
  744. return quote_from_bytes(string, safe)
  745. def quote_plus(string, safe='', encoding=None, errors=None):
  746. """Like quote(), but also replace ' ' with '+', as required for quoting
  747. HTML form values. Plus signs in the original string are escaped unless
  748. they are included in safe. It also does not have safe default to '/'.
  749. """
  750. # Check if ' ' in string, where string may either be a str or bytes. If
  751. # there are no spaces, the regular quote will produce the right answer.
  752. if ((isinstance(string, str) and ' ' not in string) or
  753. (isinstance(string, bytes) and b' ' not in string)):
  754. return quote(string, safe, encoding, errors)
  755. if isinstance(safe, str):
  756. space = ' '
  757. else:
  758. space = b' '
  759. string = quote(string, safe + space, encoding, errors)
  760. return string.replace(' ', '+')
  761. # Expectation: A typical program is unlikely to create more than 5 of these.
  762. @functools.lru_cache
  763. def _byte_quoter_factory(safe):
  764. return _Quoter(safe).__getitem__
  765. def quote_from_bytes(bs, safe='/'):
  766. """Like quote(), but accepts a bytes object rather than a str, and does
  767. not perform string-to-bytes encoding. It always returns an ASCII string.
  768. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
  769. """
  770. if not isinstance(bs, (bytes, bytearray)):
  771. raise TypeError("quote_from_bytes() expected bytes")
  772. if not bs:
  773. return ''
  774. if isinstance(safe, str):
  775. # Normalize 'safe' by converting to bytes and removing non-ASCII chars
  776. safe = safe.encode('ascii', 'ignore')
  777. else:
  778. # List comprehensions are faster than generator expressions.
  779. safe = bytes([c for c in safe if c < 128])
  780. if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
  781. return bs.decode()
  782. quoter = _byte_quoter_factory(safe)
  783. if (bs_len := len(bs)) < 200_000:
  784. return ''.join(map(quoter, bs))
  785. else:
  786. # This saves memory - https://github.com/python/cpython/issues/95865
  787. chunk_size = math.isqrt(bs_len)
  788. chunks = [''.join(map(quoter, bs[i:i+chunk_size]))
  789. for i in range(0, bs_len, chunk_size)]
  790. return ''.join(chunks)
  791. def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
  792. quote_via=quote_plus):
  793. """Encode a dict or sequence of two-element tuples into a URL query string.
  794. If any values in the query arg are sequences and doseq is true, each
  795. sequence element is converted to a separate parameter.
  796. If the query arg is a sequence of two-element tuples, the order of the
  797. parameters in the output will match the order of parameters in the
  798. input.
  799. The components of a query arg may each be either a string or a bytes type.
  800. The safe, encoding, and errors parameters are passed down to the function
  801. specified by quote_via (encoding and errors only if a component is a str).
  802. """
  803. if hasattr(query, "items"):
  804. query = query.items()
  805. else:
  806. # It's a bother at times that strings and string-like objects are
  807. # sequences.
  808. try:
  809. # non-sequence items should not work with len()
  810. # non-empty strings will fail this
  811. if len(query) and not isinstance(query[0], tuple):
  812. raise TypeError
  813. # Zero-length sequences of all types will get here and succeed,
  814. # but that's a minor nit. Since the original implementation
  815. # allowed empty dicts that type of behavior probably should be
  816. # preserved for consistency
  817. except TypeError as err:
  818. raise TypeError("not a valid non-string sequence "
  819. "or mapping object") from err
  820. l = []
  821. if not doseq:
  822. for k, v in query:
  823. if isinstance(k, bytes):
  824. k = quote_via(k, safe)
  825. else:
  826. k = quote_via(str(k), safe, encoding, errors)
  827. if isinstance(v, bytes):
  828. v = quote_via(v, safe)
  829. else:
  830. v = quote_via(str(v), safe, encoding, errors)
  831. l.append(k + '=' + v)
  832. else:
  833. for k, v in query:
  834. if isinstance(k, bytes):
  835. k = quote_via(k, safe)
  836. else:
  837. k = quote_via(str(k), safe, encoding, errors)
  838. if isinstance(v, bytes):
  839. v = quote_via(v, safe)
  840. l.append(k + '=' + v)
  841. elif isinstance(v, str):
  842. v = quote_via(v, safe, encoding, errors)
  843. l.append(k + '=' + v)
  844. else:
  845. try:
  846. # Is this a sufficient test for sequence-ness?
  847. x = len(v)
  848. except TypeError:
  849. # not a sequence
  850. v = quote_via(str(v), safe, encoding, errors)
  851. l.append(k + '=' + v)
  852. else:
  853. # loop over the sequence
  854. for elt in v:
  855. if isinstance(elt, bytes):
  856. elt = quote_via(elt, safe)
  857. else:
  858. elt = quote_via(str(elt), safe, encoding, errors)
  859. l.append(k + '=' + elt)
  860. return '&'.join(l)
  861. def to_bytes(url):
  862. warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",
  863. DeprecationWarning, stacklevel=2)
  864. return _to_bytes(url)
  865. def _to_bytes(url):
  866. """to_bytes(u"URL") --> 'URL'."""
  867. # Most URL schemes require ASCII. If that changes, the conversion
  868. # can be relaxed.
  869. # XXX get rid of to_bytes()
  870. if isinstance(url, str):
  871. try:
  872. url = url.encode("ASCII").decode()
  873. except UnicodeError:
  874. raise UnicodeError("URL " + repr(url) +
  875. " contains non-ASCII characters")
  876. return url
  877. def unwrap(url):
  878. """Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'.
  879. The string is returned unchanged if it's not a wrapped URL.
  880. """
  881. url = str(url).strip()
  882. if url[:1] == '<' and url[-1:] == '>':
  883. url = url[1:-1].strip()
  884. if url[:4] == 'URL:':
  885. url = url[4:].strip()
  886. return url
  887. def splittype(url):
  888. warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, "
  889. "use urllib.parse.urlparse() instead",
  890. DeprecationWarning, stacklevel=2)
  891. return _splittype(url)
  892. _typeprog = None
  893. def _splittype(url):
  894. """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  895. global _typeprog
  896. if _typeprog is None:
  897. _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
  898. match = _typeprog.match(url)
  899. if match:
  900. scheme, data = match.groups()
  901. return scheme.lower(), data
  902. return None, url
  903. def splithost(url):
  904. warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, "
  905. "use urllib.parse.urlparse() instead",
  906. DeprecationWarning, stacklevel=2)
  907. return _splithost(url)
  908. _hostprog = None
  909. def _splithost(url):
  910. """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  911. global _hostprog
  912. if _hostprog is None:
  913. _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
  914. match = _hostprog.match(url)
  915. if match:
  916. host_port, path = match.groups()
  917. if path and path[0] != '/':
  918. path = '/' + path
  919. return host_port, path
  920. return None, url
  921. def splituser(host):
  922. warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, "
  923. "use urllib.parse.urlparse() instead",
  924. DeprecationWarning, stacklevel=2)
  925. return _splituser(host)
  926. def _splituser(host):
  927. """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  928. user, delim, host = host.rpartition('@')
  929. return (user if delim else None), host
  930. def splitpasswd(user):
  931. warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, "
  932. "use urllib.parse.urlparse() instead",
  933. DeprecationWarning, stacklevel=2)
  934. return _splitpasswd(user)
  935. def _splitpasswd(user):
  936. """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  937. user, delim, passwd = user.partition(':')
  938. return user, (passwd if delim else None)
  939. def splitport(host):
  940. warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, "
  941. "use urllib.parse.urlparse() instead",
  942. DeprecationWarning, stacklevel=2)
  943. return _splitport(host)
  944. # splittag('/path#tag') --> '/path', 'tag'
  945. _portprog = None
  946. def _splitport(host):
  947. """splitport('host:port') --> 'host', 'port'."""
  948. global _portprog
  949. if _portprog is None:
  950. _portprog = re.compile('(.*):([0-9]*)', re.DOTALL)
  951. match = _portprog.fullmatch(host)
  952. if match:
  953. host, port = match.groups()
  954. if port:
  955. return host, port
  956. return host, None
  957. def splitnport(host, defport=-1):
  958. warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, "
  959. "use urllib.parse.urlparse() instead",
  960. DeprecationWarning, stacklevel=2)
  961. return _splitnport(host, defport)
  962. def _splitnport(host, defport=-1):
  963. """Split host and port, returning numeric port.
  964. Return given default port if no ':' found; defaults to -1.
  965. Return numerical port if a valid number is found after ':'.
  966. Return None if ':' but not a valid number."""
  967. host, delim, port = host.rpartition(':')
  968. if not delim:
  969. host = port
  970. elif port:
  971. if port.isdigit() and port.isascii():
  972. nport = int(port)
  973. else:
  974. nport = None
  975. return host, nport
  976. return host, defport
  977. def splitquery(url):
  978. warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, "
  979. "use urllib.parse.urlparse() instead",
  980. DeprecationWarning, stacklevel=2)
  981. return _splitquery(url)
  982. def _splitquery(url):
  983. """splitquery('/path?query') --> '/path', 'query'."""
  984. path, delim, query = url.rpartition('?')
  985. if delim:
  986. return path, query
  987. return url, None
  988. def splittag(url):
  989. warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, "
  990. "use urllib.parse.urlparse() instead",
  991. DeprecationWarning, stacklevel=2)
  992. return _splittag(url)
  993. def _splittag(url):
  994. """splittag('/path#tag') --> '/path', 'tag'."""
  995. path, delim, tag = url.rpartition('#')
  996. if delim:
  997. return path, tag
  998. return url, None
  999. def splitattr(url):
  1000. warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, "
  1001. "use urllib.parse.urlparse() instead",
  1002. DeprecationWarning, stacklevel=2)
  1003. return _splitattr(url)
  1004. def _splitattr(url):
  1005. """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1006. '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1007. words = url.split(';')
  1008. return words[0], words[1:]
  1009. def splitvalue(attr):
  1010. warnings.warn("urllib.parse.splitvalue() is deprecated as of 3.8, "
  1011. "use urllib.parse.parse_qsl() instead",
  1012. DeprecationWarning, stacklevel=2)
  1013. return _splitvalue(attr)
  1014. def _splitvalue(attr):
  1015. """splitvalue('attr=value') --> 'attr', 'value'."""
  1016. attr, delim, value = attr.partition('=')
  1017. return attr, (value if delim else None)