_url.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. import re
  2. import sys
  3. import warnings
  4. from collections.abc import Mapping, Sequence
  5. from enum import Enum
  6. from functools import _CacheInfo, lru_cache
  7. from ipaddress import ip_address
  8. from typing import TYPE_CHECKING, Any, NoReturn, TypedDict, TypeVar, Union, overload
  9. from urllib.parse import SplitResult, uses_relative
  10. import idna
  11. from multidict import MultiDict, MultiDictProxy
  12. from propcache.api import under_cached_property as cached_property
  13. from ._parse import (
  14. USES_AUTHORITY,
  15. SplitURLType,
  16. make_netloc,
  17. query_to_pairs,
  18. split_netloc,
  19. split_url,
  20. unsplit_result,
  21. )
  22. from ._path import normalize_path, normalize_path_segments
  23. from ._query import (
  24. Query,
  25. QueryVariable,
  26. SimpleQuery,
  27. get_str_query,
  28. get_str_query_from_iterable,
  29. get_str_query_from_sequence_iterable,
  30. )
  31. from ._quoters import (
  32. FRAGMENT_QUOTER,
  33. FRAGMENT_REQUOTER,
  34. PATH_QUOTER,
  35. PATH_REQUOTER,
  36. PATH_SAFE_UNQUOTER,
  37. PATH_UNQUOTER,
  38. QS_UNQUOTER,
  39. QUERY_QUOTER,
  40. QUERY_REQUOTER,
  41. QUOTER,
  42. REQUOTER,
  43. UNQUOTER,
  44. human_quote,
  45. )
  46. DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21}
  47. USES_RELATIVE = frozenset(uses_relative)
  48. # Special schemes https://url.spec.whatwg.org/#special-scheme
  49. # are not allowed to have an empty host https://url.spec.whatwg.org/#url-representation
  50. SCHEME_REQUIRES_HOST = frozenset(("http", "https", "ws", "wss", "ftp"))
  51. # reg-name: unreserved / pct-encoded / sub-delims
  52. # this pattern matches anything that is *not* in those classes. and is only used
  53. # on lower-cased ASCII values.
  54. NOT_REG_NAME = re.compile(
  55. r"""
  56. # any character not in the unreserved or sub-delims sets, plus %
  57. # (validated with the additional check for pct-encoded sequences below)
  58. [^a-z0-9\-._~!$&'()*+,;=%]
  59. |
  60. # % only allowed if it is part of a pct-encoded
  61. # sequence of 2 hex digits.
  62. %(?![0-9a-f]{2})
  63. """,
  64. re.VERBOSE,
  65. )
  66. _T = TypeVar("_T")
  67. if sys.version_info >= (3, 11):
  68. from typing import Self
  69. else:
  70. Self = Any
  71. class UndefinedType(Enum):
  72. """Singleton type for use with not set sentinel values."""
  73. _singleton = 0
  74. UNDEFINED = UndefinedType._singleton
  75. class CacheInfo(TypedDict):
  76. """Host encoding cache."""
  77. idna_encode: _CacheInfo
  78. idna_decode: _CacheInfo
  79. ip_address: _CacheInfo
  80. host_validate: _CacheInfo
  81. encode_host: _CacheInfo
  82. class _InternalURLCache(TypedDict, total=False):
  83. _val: SplitURLType
  84. _origin: "URL"
  85. absolute: bool
  86. hash: int
  87. scheme: str
  88. raw_authority: str
  89. authority: str
  90. raw_user: Union[str, None]
  91. user: Union[str, None]
  92. raw_password: Union[str, None]
  93. password: Union[str, None]
  94. raw_host: Union[str, None]
  95. host: Union[str, None]
  96. host_subcomponent: Union[str, None]
  97. host_port_subcomponent: Union[str, None]
  98. port: Union[int, None]
  99. explicit_port: Union[int, None]
  100. raw_path: str
  101. path: str
  102. _parsed_query: list[tuple[str, str]]
  103. query: "MultiDictProxy[str]"
  104. raw_query_string: str
  105. query_string: str
  106. path_qs: str
  107. raw_path_qs: str
  108. raw_fragment: str
  109. fragment: str
  110. raw_parts: tuple[str, ...]
  111. parts: tuple[str, ...]
  112. parent: "URL"
  113. raw_name: str
  114. name: str
  115. raw_suffix: str
  116. suffix: str
  117. raw_suffixes: tuple[str, ...]
  118. suffixes: tuple[str, ...]
  119. def rewrite_module(obj: _T) -> _T:
  120. obj.__module__ = "yarl"
  121. return obj
  122. @lru_cache
  123. def encode_url(url_str: str) -> "URL":
  124. """Parse unencoded URL."""
  125. cache: _InternalURLCache = {}
  126. host: Union[str, None]
  127. scheme, netloc, path, query, fragment = split_url(url_str)
  128. if not netloc: # netloc
  129. host = ""
  130. else:
  131. if ":" in netloc or "@" in netloc or "[" in netloc:
  132. # Complex netloc
  133. username, password, host, port = split_netloc(netloc)
  134. else:
  135. username = password = port = None
  136. host = netloc
  137. if host is None:
  138. if scheme in SCHEME_REQUIRES_HOST:
  139. msg = (
  140. "Invalid URL: host is required for "
  141. f"absolute urls with the {scheme} scheme"
  142. )
  143. raise ValueError(msg)
  144. else:
  145. host = ""
  146. host = _encode_host(host, validate_host=False)
  147. # Remove brackets as host encoder adds back brackets for IPv6 addresses
  148. cache["raw_host"] = host[1:-1] if "[" in host else host
  149. cache["explicit_port"] = port
  150. if password is None and username is None:
  151. # Fast path for URLs without user, password
  152. netloc = host if port is None else f"{host}:{port}"
  153. cache["raw_user"] = None
  154. cache["raw_password"] = None
  155. else:
  156. raw_user = REQUOTER(username) if username else username
  157. raw_password = REQUOTER(password) if password else password
  158. netloc = make_netloc(raw_user, raw_password, host, port)
  159. cache["raw_user"] = raw_user
  160. cache["raw_password"] = raw_password
  161. if path:
  162. path = PATH_REQUOTER(path)
  163. if netloc and "." in path:
  164. path = normalize_path(path)
  165. if query:
  166. query = QUERY_REQUOTER(query)
  167. if fragment:
  168. fragment = FRAGMENT_REQUOTER(fragment)
  169. cache["scheme"] = scheme
  170. cache["raw_path"] = "/" if not path and netloc else path
  171. cache["raw_query_string"] = query
  172. cache["raw_fragment"] = fragment
  173. self = object.__new__(URL)
  174. self._scheme = scheme
  175. self._netloc = netloc
  176. self._path = path
  177. self._query = query
  178. self._fragment = fragment
  179. self._cache = cache
  180. return self
  181. @lru_cache
  182. def pre_encoded_url(url_str: str) -> "URL":
  183. """Parse pre-encoded URL."""
  184. self = object.__new__(URL)
  185. val = split_url(url_str)
  186. self._scheme, self._netloc, self._path, self._query, self._fragment = val
  187. self._cache = {}
  188. return self
  189. @lru_cache
  190. def build_pre_encoded_url(
  191. scheme: str,
  192. authority: str,
  193. user: Union[str, None],
  194. password: Union[str, None],
  195. host: str,
  196. port: Union[int, None],
  197. path: str,
  198. query_string: str,
  199. fragment: str,
  200. ) -> "URL":
  201. """Build a pre-encoded URL from parts."""
  202. self = object.__new__(URL)
  203. self._scheme = scheme
  204. if authority:
  205. self._netloc = authority
  206. elif host:
  207. if port is not None:
  208. port = None if port == DEFAULT_PORTS.get(scheme) else port
  209. if user is None and password is None:
  210. self._netloc = host if port is None else f"{host}:{port}"
  211. else:
  212. self._netloc = make_netloc(user, password, host, port)
  213. else:
  214. self._netloc = ""
  215. self._path = path
  216. self._query = query_string
  217. self._fragment = fragment
  218. self._cache = {}
  219. return self
  220. def from_parts_uncached(
  221. scheme: str, netloc: str, path: str, query: str, fragment: str
  222. ) -> "URL":
  223. """Create a new URL from parts."""
  224. self = object.__new__(URL)
  225. self._scheme = scheme
  226. self._netloc = netloc
  227. self._path = path
  228. self._query = query
  229. self._fragment = fragment
  230. self._cache = {}
  231. return self
  232. from_parts = lru_cache(from_parts_uncached)
  233. @rewrite_module
  234. class URL:
  235. # Don't derive from str
  236. # follow pathlib.Path design
  237. # probably URL will not suffer from pathlib problems:
  238. # it's intended for libraries like aiohttp,
  239. # not to be passed into standard library functions like os.open etc.
  240. # URL grammar (RFC 3986)
  241. # pct-encoded = "%" HEXDIG HEXDIG
  242. # reserved = gen-delims / sub-delims
  243. # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
  244. # sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  245. # / "*" / "+" / "," / ";" / "="
  246. # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  247. # URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
  248. # hier-part = "//" authority path-abempty
  249. # / path-absolute
  250. # / path-rootless
  251. # / path-empty
  252. # scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  253. # authority = [ userinfo "@" ] host [ ":" port ]
  254. # userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
  255. # host = IP-literal / IPv4address / reg-name
  256. # IP-literal = "[" ( IPv6address / IPvFuture ) "]"
  257. # IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
  258. # IPv6address = 6( h16 ":" ) ls32
  259. # / "::" 5( h16 ":" ) ls32
  260. # / [ h16 ] "::" 4( h16 ":" ) ls32
  261. # / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
  262. # / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
  263. # / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
  264. # / [ *4( h16 ":" ) h16 ] "::" ls32
  265. # / [ *5( h16 ":" ) h16 ] "::" h16
  266. # / [ *6( h16 ":" ) h16 ] "::"
  267. # ls32 = ( h16 ":" h16 ) / IPv4address
  268. # ; least-significant 32 bits of address
  269. # h16 = 1*4HEXDIG
  270. # ; 16 bits of address represented in hexadecimal
  271. # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
  272. # dec-octet = DIGIT ; 0-9
  273. # / %x31-39 DIGIT ; 10-99
  274. # / "1" 2DIGIT ; 100-199
  275. # / "2" %x30-34 DIGIT ; 200-249
  276. # / "25" %x30-35 ; 250-255
  277. # reg-name = *( unreserved / pct-encoded / sub-delims )
  278. # port = *DIGIT
  279. # path = path-abempty ; begins with "/" or is empty
  280. # / path-absolute ; begins with "/" but not "//"
  281. # / path-noscheme ; begins with a non-colon segment
  282. # / path-rootless ; begins with a segment
  283. # / path-empty ; zero characters
  284. # path-abempty = *( "/" segment )
  285. # path-absolute = "/" [ segment-nz *( "/" segment ) ]
  286. # path-noscheme = segment-nz-nc *( "/" segment )
  287. # path-rootless = segment-nz *( "/" segment )
  288. # path-empty = 0<pchar>
  289. # segment = *pchar
  290. # segment-nz = 1*pchar
  291. # segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
  292. # ; non-zero-length segment without any colon ":"
  293. # pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  294. # query = *( pchar / "/" / "?" )
  295. # fragment = *( pchar / "/" / "?" )
  296. # URI-reference = URI / relative-ref
  297. # relative-ref = relative-part [ "?" query ] [ "#" fragment ]
  298. # relative-part = "//" authority path-abempty
  299. # / path-absolute
  300. # / path-noscheme
  301. # / path-empty
  302. # absolute-URI = scheme ":" hier-part [ "?" query ]
  303. __slots__ = ("_cache", "_scheme", "_netloc", "_path", "_query", "_fragment")
  304. _cache: _InternalURLCache
  305. _scheme: str
  306. _netloc: str
  307. _path: str
  308. _query: str
  309. _fragment: str
  310. def __new__(
  311. cls,
  312. val: Union[str, SplitResult, "URL", UndefinedType] = UNDEFINED,
  313. *,
  314. encoded: bool = False,
  315. strict: Union[bool, None] = None,
  316. ) -> "URL":
  317. if strict is not None: # pragma: no cover
  318. warnings.warn("strict parameter is ignored")
  319. if type(val) is str:
  320. return pre_encoded_url(val) if encoded else encode_url(val)
  321. if type(val) is cls:
  322. return val
  323. if type(val) is SplitResult:
  324. if not encoded:
  325. raise ValueError("Cannot apply decoding to SplitResult")
  326. return from_parts(*val)
  327. if isinstance(val, str):
  328. return pre_encoded_url(str(val)) if encoded else encode_url(str(val))
  329. if val is UNDEFINED:
  330. # Special case for UNDEFINED since it might be unpickling and we do
  331. # not want to cache as the `__set_state__` call would mutate the URL
  332. # object in the `pre_encoded_url` or `encoded_url` caches.
  333. self = object.__new__(URL)
  334. self._scheme = self._netloc = self._path = self._query = self._fragment = ""
  335. self._cache = {}
  336. return self
  337. raise TypeError("Constructor parameter should be str")
  338. @classmethod
  339. def build(
  340. cls,
  341. *,
  342. scheme: str = "",
  343. authority: str = "",
  344. user: Union[str, None] = None,
  345. password: Union[str, None] = None,
  346. host: str = "",
  347. port: Union[int, None] = None,
  348. path: str = "",
  349. query: Union[Query, None] = None,
  350. query_string: str = "",
  351. fragment: str = "",
  352. encoded: bool = False,
  353. ) -> "URL":
  354. """Creates and returns a new URL"""
  355. if authority and (user or password or host or port):
  356. raise ValueError(
  357. 'Can\'t mix "authority" with "user", "password", "host" or "port".'
  358. )
  359. if port is not None and not isinstance(port, int):
  360. raise TypeError(f"The port is required to be int, got {type(port)!r}.")
  361. if port and not host:
  362. raise ValueError('Can\'t build URL with "port" but without "host".')
  363. if query and query_string:
  364. raise ValueError('Only one of "query" or "query_string" should be passed')
  365. if (
  366. scheme is None # type: ignore[redundant-expr]
  367. or authority is None # type: ignore[redundant-expr]
  368. or host is None # type: ignore[redundant-expr]
  369. or path is None # type: ignore[redundant-expr]
  370. or query_string is None # type: ignore[redundant-expr]
  371. or fragment is None
  372. ):
  373. raise TypeError(
  374. 'NoneType is illegal for "scheme", "authority", "host", "path", '
  375. '"query_string", and "fragment" args, use empty string instead.'
  376. )
  377. if query:
  378. query_string = get_str_query(query) or ""
  379. if encoded:
  380. return build_pre_encoded_url(
  381. scheme,
  382. authority,
  383. user,
  384. password,
  385. host,
  386. port,
  387. path,
  388. query_string,
  389. fragment,
  390. )
  391. self = object.__new__(URL)
  392. self._scheme = scheme
  393. _host: Union[str, None] = None
  394. if authority:
  395. user, password, _host, port = split_netloc(authority)
  396. _host = _encode_host(_host, validate_host=False) if _host else ""
  397. elif host:
  398. _host = _encode_host(host, validate_host=True)
  399. else:
  400. self._netloc = ""
  401. if _host is not None:
  402. if port is not None:
  403. port = None if port == DEFAULT_PORTS.get(scheme) else port
  404. if user is None and password is None:
  405. self._netloc = _host if port is None else f"{_host}:{port}"
  406. else:
  407. self._netloc = make_netloc(user, password, _host, port, True)
  408. path = PATH_QUOTER(path) if path else path
  409. if path and self._netloc:
  410. if "." in path:
  411. path = normalize_path(path)
  412. if path[0] != "/":
  413. msg = (
  414. "Path in a URL with authority should "
  415. "start with a slash ('/') if set"
  416. )
  417. raise ValueError(msg)
  418. self._path = path
  419. if not query and query_string:
  420. query_string = QUERY_QUOTER(query_string)
  421. self._query = query_string
  422. self._fragment = FRAGMENT_QUOTER(fragment) if fragment else fragment
  423. self._cache = {}
  424. return self
  425. def __init_subclass__(cls) -> NoReturn:
  426. raise TypeError(f"Inheriting a class {cls!r} from URL is forbidden")
  427. def __str__(self) -> str:
  428. if not self._path and self._netloc and (self._query or self._fragment):
  429. path = "/"
  430. else:
  431. path = self._path
  432. if (port := self.explicit_port) is not None and port == DEFAULT_PORTS.get(
  433. self._scheme
  434. ):
  435. # port normalization - using None for default ports to remove from rendering
  436. # https://datatracker.ietf.org/doc/html/rfc3986.html#section-6.2.3
  437. host = self.host_subcomponent
  438. netloc = make_netloc(self.raw_user, self.raw_password, host, None)
  439. else:
  440. netloc = self._netloc
  441. return unsplit_result(self._scheme, netloc, path, self._query, self._fragment)
  442. def __repr__(self) -> str:
  443. return f"{self.__class__.__name__}('{str(self)}')"
  444. def __bytes__(self) -> bytes:
  445. return str(self).encode("ascii")
  446. def __eq__(self, other: object) -> bool:
  447. if type(other) is not URL:
  448. return NotImplemented
  449. path1 = "/" if not self._path and self._netloc else self._path
  450. path2 = "/" if not other._path and other._netloc else other._path
  451. return (
  452. self._scheme == other._scheme
  453. and self._netloc == other._netloc
  454. and path1 == path2
  455. and self._query == other._query
  456. and self._fragment == other._fragment
  457. )
  458. def __hash__(self) -> int:
  459. if (ret := self._cache.get("hash")) is None:
  460. path = "/" if not self._path and self._netloc else self._path
  461. ret = self._cache["hash"] = hash(
  462. (self._scheme, self._netloc, path, self._query, self._fragment)
  463. )
  464. return ret
  465. def __le__(self, other: object) -> bool:
  466. if type(other) is not URL:
  467. return NotImplemented
  468. return self._val <= other._val
  469. def __lt__(self, other: object) -> bool:
  470. if type(other) is not URL:
  471. return NotImplemented
  472. return self._val < other._val
  473. def __ge__(self, other: object) -> bool:
  474. if type(other) is not URL:
  475. return NotImplemented
  476. return self._val >= other._val
  477. def __gt__(self, other: object) -> bool:
  478. if type(other) is not URL:
  479. return NotImplemented
  480. return self._val > other._val
  481. def __truediv__(self, name: str) -> "URL":
  482. if not isinstance(name, str):
  483. return NotImplemented # type: ignore[unreachable]
  484. return self._make_child((str(name),))
  485. def __mod__(self, query: Query) -> "URL":
  486. return self.update_query(query)
  487. def __bool__(self) -> bool:
  488. return bool(self._netloc or self._path or self._query or self._fragment)
  489. def __getstate__(self) -> tuple[SplitResult]:
  490. return (tuple.__new__(SplitResult, self._val),)
  491. def __setstate__(
  492. self, state: Union[tuple[SplitURLType], tuple[None, _InternalURLCache]]
  493. ) -> None:
  494. if state[0] is None and isinstance(state[1], dict):
  495. # default style pickle
  496. val = state[1]["_val"]
  497. else:
  498. unused: list[object]
  499. val, *unused = state
  500. self._scheme, self._netloc, self._path, self._query, self._fragment = val
  501. self._cache = {}
  502. def _cache_netloc(self) -> None:
  503. """Cache the netloc parts of the URL."""
  504. c = self._cache
  505. split_loc = split_netloc(self._netloc)
  506. c["raw_user"], c["raw_password"], c["raw_host"], c["explicit_port"] = split_loc
  507. def is_absolute(self) -> bool:
  508. """A check for absolute URLs.
  509. Return True for absolute ones (having scheme or starting
  510. with //), False otherwise.
  511. Is is preferred to call the .absolute property instead
  512. as it is cached.
  513. """
  514. return self.absolute
  515. def is_default_port(self) -> bool:
  516. """A check for default port.
  517. Return True if port is default for specified scheme,
  518. e.g. 'http://python.org' or 'http://python.org:80', False
  519. otherwise.
  520. Return False for relative URLs.
  521. """
  522. if (explicit := self.explicit_port) is None:
  523. # If the explicit port is None, then the URL must be
  524. # using the default port unless its a relative URL
  525. # which does not have an implicit port / default port
  526. return self._netloc != ""
  527. return explicit == DEFAULT_PORTS.get(self._scheme)
  528. def origin(self) -> "URL":
  529. """Return an URL with scheme, host and port parts only.
  530. user, password, path, query and fragment are removed.
  531. """
  532. # TODO: add a keyword-only option for keeping user/pass maybe?
  533. return self._origin
  534. @cached_property
  535. def _val(self) -> SplitURLType:
  536. return (self._scheme, self._netloc, self._path, self._query, self._fragment)
  537. @cached_property
  538. def _origin(self) -> "URL":
  539. """Return an URL with scheme, host and port parts only.
  540. user, password, path, query and fragment are removed.
  541. """
  542. if not (netloc := self._netloc):
  543. raise ValueError("URL should be absolute")
  544. if not (scheme := self._scheme):
  545. raise ValueError("URL should have scheme")
  546. if "@" in netloc:
  547. encoded_host = self.host_subcomponent
  548. netloc = make_netloc(None, None, encoded_host, self.explicit_port)
  549. elif not self._path and not self._query and not self._fragment:
  550. return self
  551. return from_parts(scheme, netloc, "", "", "")
  552. def relative(self) -> "URL":
  553. """Return a relative part of the URL.
  554. scheme, user, password, host and port are removed.
  555. """
  556. if not self._netloc:
  557. raise ValueError("URL should be absolute")
  558. return from_parts("", "", self._path, self._query, self._fragment)
  559. @cached_property
  560. def absolute(self) -> bool:
  561. """A check for absolute URLs.
  562. Return True for absolute ones (having scheme or starting
  563. with //), False otherwise.
  564. """
  565. # `netloc`` is an empty string for relative URLs
  566. # Checking `netloc` is faster than checking `hostname`
  567. # because `hostname` is a property that does some extra work
  568. # to parse the host from the `netloc`
  569. return self._netloc != ""
  570. @cached_property
  571. def scheme(self) -> str:
  572. """Scheme for absolute URLs.
  573. Empty string for relative URLs or URLs starting with //
  574. """
  575. return self._scheme
  576. @cached_property
  577. def raw_authority(self) -> str:
  578. """Encoded authority part of URL.
  579. Empty string for relative URLs.
  580. """
  581. return self._netloc
  582. @cached_property
  583. def authority(self) -> str:
  584. """Decoded authority part of URL.
  585. Empty string for relative URLs.
  586. """
  587. return make_netloc(self.user, self.password, self.host, self.port)
  588. @cached_property
  589. def raw_user(self) -> Union[str, None]:
  590. """Encoded user part of URL.
  591. None if user is missing.
  592. """
  593. # not .username
  594. self._cache_netloc()
  595. return self._cache["raw_user"]
  596. @cached_property
  597. def user(self) -> Union[str, None]:
  598. """Decoded user part of URL.
  599. None if user is missing.
  600. """
  601. if (raw_user := self.raw_user) is None:
  602. return None
  603. return UNQUOTER(raw_user)
  604. @cached_property
  605. def raw_password(self) -> Union[str, None]:
  606. """Encoded password part of URL.
  607. None if password is missing.
  608. """
  609. self._cache_netloc()
  610. return self._cache["raw_password"]
  611. @cached_property
  612. def password(self) -> Union[str, None]:
  613. """Decoded password part of URL.
  614. None if password is missing.
  615. """
  616. if (raw_password := self.raw_password) is None:
  617. return None
  618. return UNQUOTER(raw_password)
  619. @cached_property
  620. def raw_host(self) -> Union[str, None]:
  621. """Encoded host part of URL.
  622. None for relative URLs.
  623. When working with IPv6 addresses, use the `host_subcomponent` property instead
  624. as it will return the host subcomponent with brackets.
  625. """
  626. # Use host instead of hostname for sake of shortness
  627. # May add .hostname prop later
  628. self._cache_netloc()
  629. return self._cache["raw_host"]
  630. @cached_property
  631. def host(self) -> Union[str, None]:
  632. """Decoded host part of URL.
  633. None for relative URLs.
  634. """
  635. if (raw := self.raw_host) is None:
  636. return None
  637. if raw and raw[-1].isdigit() or ":" in raw:
  638. # IP addresses are never IDNA encoded
  639. return raw
  640. return _idna_decode(raw)
  641. @cached_property
  642. def host_subcomponent(self) -> Union[str, None]:
  643. """Return the host subcomponent part of URL.
  644. None for relative URLs.
  645. https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2
  646. `IP-literal = "[" ( IPv6address / IPvFuture ) "]"`
  647. Examples:
  648. - `http://example.com:8080` -> `example.com`
  649. - `http://example.com:80` -> `example.com`
  650. - `https://127.0.0.1:8443` -> `127.0.0.1`
  651. - `https://[::1]:8443` -> `[::1]`
  652. - `http://[::1]` -> `[::1]`
  653. """
  654. if (raw := self.raw_host) is None:
  655. return None
  656. return f"[{raw}]" if ":" in raw else raw
  657. @cached_property
  658. def host_port_subcomponent(self) -> Union[str, None]:
  659. """Return the host and port subcomponent part of URL.
  660. Trailing dots are removed from the host part.
  661. This value is suitable for use in the Host header of an HTTP request.
  662. None for relative URLs.
  663. https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2
  664. `IP-literal = "[" ( IPv6address / IPvFuture ) "]"`
  665. https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.3
  666. port = *DIGIT
  667. Examples:
  668. - `http://example.com:8080` -> `example.com:8080`
  669. - `http://example.com:80` -> `example.com`
  670. - `http://example.com.:80` -> `example.com`
  671. - `https://127.0.0.1:8443` -> `127.0.0.1:8443`
  672. - `https://[::1]:8443` -> `[::1]:8443`
  673. - `http://[::1]` -> `[::1]`
  674. """
  675. if (raw := self.raw_host) is None:
  676. return None
  677. if raw[-1] == ".":
  678. # Remove all trailing dots from the netloc as while
  679. # they are valid FQDNs in DNS, TLS validation fails.
  680. # See https://github.com/aio-libs/aiohttp/issues/3636.
  681. # To avoid string manipulation we only call rstrip if
  682. # the last character is a dot.
  683. raw = raw.rstrip(".")
  684. port = self.explicit_port
  685. if port is None or port == DEFAULT_PORTS.get(self._scheme):
  686. return f"[{raw}]" if ":" in raw else raw
  687. return f"[{raw}]:{port}" if ":" in raw else f"{raw}:{port}"
  688. @cached_property
  689. def port(self) -> Union[int, None]:
  690. """Port part of URL, with scheme-based fallback.
  691. None for relative URLs or URLs without explicit port and
  692. scheme without default port substitution.
  693. """
  694. if (explicit_port := self.explicit_port) is not None:
  695. return explicit_port
  696. return DEFAULT_PORTS.get(self._scheme)
  697. @cached_property
  698. def explicit_port(self) -> Union[int, None]:
  699. """Port part of URL, without scheme-based fallback.
  700. None for relative URLs or URLs without explicit port.
  701. """
  702. self._cache_netloc()
  703. return self._cache["explicit_port"]
  704. @cached_property
  705. def raw_path(self) -> str:
  706. """Encoded path of URL.
  707. / for absolute URLs without path part.
  708. """
  709. return self._path if self._path or not self._netloc else "/"
  710. @cached_property
  711. def path(self) -> str:
  712. """Decoded path of URL.
  713. / for absolute URLs without path part.
  714. """
  715. return PATH_UNQUOTER(self._path) if self._path else "/" if self._netloc else ""
  716. @cached_property
  717. def path_safe(self) -> str:
  718. """Decoded path of URL.
  719. / for absolute URLs without path part.
  720. / (%2F) and % (%25) are not decoded
  721. """
  722. if self._path:
  723. return PATH_SAFE_UNQUOTER(self._path)
  724. return "/" if self._netloc else ""
  725. @cached_property
  726. def _parsed_query(self) -> list[tuple[str, str]]:
  727. """Parse query part of URL."""
  728. return query_to_pairs(self._query)
  729. @cached_property
  730. def query(self) -> "MultiDictProxy[str]":
  731. """A MultiDictProxy representing parsed query parameters in decoded
  732. representation.
  733. Empty value if URL has no query part.
  734. """
  735. return MultiDictProxy(MultiDict(self._parsed_query))
  736. @cached_property
  737. def raw_query_string(self) -> str:
  738. """Encoded query part of URL.
  739. Empty string if query is missing.
  740. """
  741. return self._query
  742. @cached_property
  743. def query_string(self) -> str:
  744. """Decoded query part of URL.
  745. Empty string if query is missing.
  746. """
  747. return QS_UNQUOTER(self._query) if self._query else ""
  748. @cached_property
  749. def path_qs(self) -> str:
  750. """Decoded path of URL with query."""
  751. return self.path if not (q := self.query_string) else f"{self.path}?{q}"
  752. @cached_property
  753. def raw_path_qs(self) -> str:
  754. """Encoded path of URL with query."""
  755. if q := self._query:
  756. return f"{self._path}?{q}" if self._path or not self._netloc else f"/?{q}"
  757. return self._path if self._path or not self._netloc else "/"
  758. @cached_property
  759. def raw_fragment(self) -> str:
  760. """Encoded fragment part of URL.
  761. Empty string if fragment is missing.
  762. """
  763. return self._fragment
  764. @cached_property
  765. def fragment(self) -> str:
  766. """Decoded fragment part of URL.
  767. Empty string if fragment is missing.
  768. """
  769. return UNQUOTER(self._fragment) if self._fragment else ""
  770. @cached_property
  771. def raw_parts(self) -> tuple[str, ...]:
  772. """A tuple containing encoded *path* parts.
  773. ('/',) for absolute URLs if *path* is missing.
  774. """
  775. path = self._path
  776. if self._netloc:
  777. return ("/", *path[1:].split("/")) if path else ("/",)
  778. if path and path[0] == "/":
  779. return ("/", *path[1:].split("/"))
  780. return tuple(path.split("/"))
  781. @cached_property
  782. def parts(self) -> tuple[str, ...]:
  783. """A tuple containing decoded *path* parts.
  784. ('/',) for absolute URLs if *path* is missing.
  785. """
  786. return tuple(UNQUOTER(part) for part in self.raw_parts)
  787. @cached_property
  788. def parent(self) -> "URL":
  789. """A new URL with last part of path removed and cleaned up query and
  790. fragment.
  791. """
  792. path = self._path
  793. if not path or path == "/":
  794. if self._fragment or self._query:
  795. return from_parts(self._scheme, self._netloc, path, "", "")
  796. return self
  797. parts = path.split("/")
  798. return from_parts(self._scheme, self._netloc, "/".join(parts[:-1]), "", "")
  799. @cached_property
  800. def raw_name(self) -> str:
  801. """The last part of raw_parts."""
  802. parts = self.raw_parts
  803. if not self._netloc:
  804. return parts[-1]
  805. parts = parts[1:]
  806. return parts[-1] if parts else ""
  807. @cached_property
  808. def name(self) -> str:
  809. """The last part of parts."""
  810. return UNQUOTER(self.raw_name)
  811. @cached_property
  812. def raw_suffix(self) -> str:
  813. name = self.raw_name
  814. i = name.rfind(".")
  815. return name[i:] if 0 < i < len(name) - 1 else ""
  816. @cached_property
  817. def suffix(self) -> str:
  818. return UNQUOTER(self.raw_suffix)
  819. @cached_property
  820. def raw_suffixes(self) -> tuple[str, ...]:
  821. name = self.raw_name
  822. if name.endswith("."):
  823. return ()
  824. name = name.lstrip(".")
  825. return tuple("." + suffix for suffix in name.split(".")[1:])
  826. @cached_property
  827. def suffixes(self) -> tuple[str, ...]:
  828. return tuple(UNQUOTER(suffix) for suffix in self.raw_suffixes)
  829. def _make_child(self, paths: "Sequence[str]", encoded: bool = False) -> "URL":
  830. """
  831. add paths to self._path, accounting for absolute vs relative paths,
  832. keep existing, but do not create new, empty segments
  833. """
  834. parsed: list[str] = []
  835. needs_normalize: bool = False
  836. for idx, path in enumerate(reversed(paths)):
  837. # empty segment of last is not removed
  838. last = idx == 0
  839. if path and path[0] == "/":
  840. raise ValueError(
  841. f"Appending path {path!r} starting from slash is forbidden"
  842. )
  843. # We need to quote the path if it is not already encoded
  844. # This cannot be done at the end because the existing
  845. # path is already quoted and we do not want to double quote
  846. # the existing path.
  847. path = path if encoded else PATH_QUOTER(path)
  848. needs_normalize |= "." in path
  849. segments = path.split("/")
  850. segments.reverse()
  851. # remove trailing empty segment for all but the last path
  852. parsed += segments[1:] if not last and segments[0] == "" else segments
  853. if (path := self._path) and (old_segments := path.split("/")):
  854. # If the old path ends with a slash, the last segment is an empty string
  855. # and should be removed before adding the new path segments.
  856. old = old_segments[:-1] if old_segments[-1] == "" else old_segments
  857. old.reverse()
  858. parsed += old
  859. # If the netloc is present, inject a leading slash when adding a
  860. # path to an absolute URL where there was none before.
  861. if (netloc := self._netloc) and parsed and parsed[-1] != "":
  862. parsed.append("")
  863. parsed.reverse()
  864. if not netloc or not needs_normalize:
  865. return from_parts(self._scheme, netloc, "/".join(parsed), "", "")
  866. path = "/".join(normalize_path_segments(parsed))
  867. # If normalizing the path segments removed the leading slash, add it back.
  868. if path and path[0] != "/":
  869. path = f"/{path}"
  870. return from_parts(self._scheme, netloc, path, "", "")
  871. def with_scheme(self, scheme: str) -> "URL":
  872. """Return a new URL with scheme replaced."""
  873. # N.B. doesn't cleanup query/fragment
  874. if not isinstance(scheme, str):
  875. raise TypeError("Invalid scheme type")
  876. lower_scheme = scheme.lower()
  877. netloc = self._netloc
  878. if not netloc and lower_scheme in SCHEME_REQUIRES_HOST:
  879. msg = (
  880. "scheme replacement is not allowed for "
  881. f"relative URLs for the {lower_scheme} scheme"
  882. )
  883. raise ValueError(msg)
  884. return from_parts(lower_scheme, netloc, self._path, self._query, self._fragment)
  885. def with_user(self, user: Union[str, None]) -> "URL":
  886. """Return a new URL with user replaced.
  887. Autoencode user if needed.
  888. Clear user/password if user is None.
  889. """
  890. # N.B. doesn't cleanup query/fragment
  891. if user is None:
  892. password = None
  893. elif isinstance(user, str):
  894. user = QUOTER(user)
  895. password = self.raw_password
  896. else:
  897. raise TypeError("Invalid user type")
  898. if not (netloc := self._netloc):
  899. raise ValueError("user replacement is not allowed for relative URLs")
  900. encoded_host = self.host_subcomponent or ""
  901. netloc = make_netloc(user, password, encoded_host, self.explicit_port)
  902. return from_parts(self._scheme, netloc, self._path, self._query, self._fragment)
  903. def with_password(self, password: Union[str, None]) -> "URL":
  904. """Return a new URL with password replaced.
  905. Autoencode password if needed.
  906. Clear password if argument is None.
  907. """
  908. # N.B. doesn't cleanup query/fragment
  909. if password is None:
  910. pass
  911. elif isinstance(password, str):
  912. password = QUOTER(password)
  913. else:
  914. raise TypeError("Invalid password type")
  915. if not (netloc := self._netloc):
  916. raise ValueError("password replacement is not allowed for relative URLs")
  917. encoded_host = self.host_subcomponent or ""
  918. port = self.explicit_port
  919. netloc = make_netloc(self.raw_user, password, encoded_host, port)
  920. return from_parts(self._scheme, netloc, self._path, self._query, self._fragment)
  921. def with_host(self, host: str) -> "URL":
  922. """Return a new URL with host replaced.
  923. Autoencode host if needed.
  924. Changing host for relative URLs is not allowed, use .join()
  925. instead.
  926. """
  927. # N.B. doesn't cleanup query/fragment
  928. if not isinstance(host, str):
  929. raise TypeError("Invalid host type")
  930. if not (netloc := self._netloc):
  931. raise ValueError("host replacement is not allowed for relative URLs")
  932. if not host:
  933. raise ValueError("host removing is not allowed")
  934. encoded_host = _encode_host(host, validate_host=True) if host else ""
  935. port = self.explicit_port
  936. netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port)
  937. return from_parts(self._scheme, netloc, self._path, self._query, self._fragment)
  938. def with_port(self, port: Union[int, None]) -> "URL":
  939. """Return a new URL with port replaced.
  940. Clear port to default if None is passed.
  941. """
  942. # N.B. doesn't cleanup query/fragment
  943. if port is not None:
  944. if isinstance(port, bool) or not isinstance(port, int):
  945. raise TypeError(f"port should be int or None, got {type(port)}")
  946. if not (0 <= port <= 65535):
  947. raise ValueError(f"port must be between 0 and 65535, got {port}")
  948. if not (netloc := self._netloc):
  949. raise ValueError("port replacement is not allowed for relative URLs")
  950. encoded_host = self.host_subcomponent or ""
  951. netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port)
  952. return from_parts(self._scheme, netloc, self._path, self._query, self._fragment)
  953. def with_path(
  954. self,
  955. path: str,
  956. *,
  957. encoded: bool = False,
  958. keep_query: bool = False,
  959. keep_fragment: bool = False,
  960. ) -> "URL":
  961. """Return a new URL with path replaced."""
  962. netloc = self._netloc
  963. if not encoded:
  964. path = PATH_QUOTER(path)
  965. if netloc:
  966. path = normalize_path(path) if "." in path else path
  967. if path and path[0] != "/":
  968. path = f"/{path}"
  969. query = self._query if keep_query else ""
  970. fragment = self._fragment if keep_fragment else ""
  971. return from_parts(self._scheme, netloc, path, query, fragment)
  972. @overload
  973. def with_query(self, query: Query) -> "URL": ...
  974. @overload
  975. def with_query(self, **kwargs: QueryVariable) -> "URL": ...
  976. def with_query(self, *args: Any, **kwargs: Any) -> "URL":
  977. """Return a new URL with query part replaced.
  978. Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
  979. or str, autoencode the argument if needed.
  980. A sequence of (key, value) pairs is supported as well.
  981. It also can take an arbitrary number of keyword arguments.
  982. Clear query if None is passed.
  983. """
  984. # N.B. doesn't cleanup query/fragment
  985. query = get_str_query(*args, **kwargs) or ""
  986. return from_parts_uncached(
  987. self._scheme, self._netloc, self._path, query, self._fragment
  988. )
  989. @overload
  990. def extend_query(self, query: Query) -> "URL": ...
  991. @overload
  992. def extend_query(self, **kwargs: QueryVariable) -> "URL": ...
  993. def extend_query(self, *args: Any, **kwargs: Any) -> "URL":
  994. """Return a new URL with query part combined with the existing.
  995. This method will not remove existing query parameters.
  996. Example:
  997. >>> url = URL('http://example.com/?a=1&b=2')
  998. >>> url.extend_query(a=3, c=4)
  999. URL('http://example.com/?a=1&b=2&a=3&c=4')
  1000. """
  1001. if not (new_query := get_str_query(*args, **kwargs)):
  1002. return self
  1003. if query := self._query:
  1004. # both strings are already encoded so we can use a simple
  1005. # string join
  1006. query += new_query if query[-1] == "&" else f"&{new_query}"
  1007. else:
  1008. query = new_query
  1009. return from_parts_uncached(
  1010. self._scheme, self._netloc, self._path, query, self._fragment
  1011. )
  1012. @overload
  1013. def update_query(self, query: Query) -> "URL": ...
  1014. @overload
  1015. def update_query(self, **kwargs: QueryVariable) -> "URL": ...
  1016. def update_query(self, *args: Any, **kwargs: Any) -> "URL":
  1017. """Return a new URL with query part updated.
  1018. This method will overwrite existing query parameters.
  1019. Example:
  1020. >>> url = URL('http://example.com/?a=1&b=2')
  1021. >>> url.update_query(a=3, c=4)
  1022. URL('http://example.com/?a=3&b=2&c=4')
  1023. """
  1024. in_query: Union[str, Mapping[str, QueryVariable], None]
  1025. if kwargs:
  1026. if args:
  1027. msg = "Either kwargs or single query parameter must be present"
  1028. raise ValueError(msg)
  1029. in_query = kwargs
  1030. elif len(args) == 1:
  1031. in_query = args[0]
  1032. else:
  1033. raise ValueError("Either kwargs or single query parameter must be present")
  1034. if in_query is None:
  1035. query = ""
  1036. elif not in_query:
  1037. query = self._query
  1038. elif isinstance(in_query, Mapping):
  1039. qm: MultiDict[QueryVariable] = MultiDict(self._parsed_query)
  1040. qm.update(in_query)
  1041. query = get_str_query_from_sequence_iterable(qm.items())
  1042. elif isinstance(in_query, str):
  1043. qstr: MultiDict[str] = MultiDict(self._parsed_query)
  1044. qstr.update(query_to_pairs(in_query))
  1045. query = get_str_query_from_iterable(qstr.items())
  1046. elif isinstance(in_query, (bytes, bytearray, memoryview)): # type: ignore[unreachable]
  1047. msg = "Invalid query type: bytes, bytearray and memoryview are forbidden"
  1048. raise TypeError(msg)
  1049. elif isinstance(in_query, Sequence):
  1050. # We don't expect sequence values if we're given a list of pairs
  1051. # already; only mappings like builtin `dict` which can't have the
  1052. # same key pointing to multiple values are allowed to use
  1053. # `_query_seq_pairs`.
  1054. qs: MultiDict[SimpleQuery] = MultiDict(self._parsed_query)
  1055. qs.update(in_query)
  1056. query = get_str_query_from_iterable(qs.items())
  1057. else:
  1058. raise TypeError(
  1059. "Invalid query type: only str, mapping or "
  1060. "sequence of (key, value) pairs is allowed"
  1061. )
  1062. return from_parts_uncached(
  1063. self._scheme, self._netloc, self._path, query, self._fragment
  1064. )
  1065. def without_query_params(self, *query_params: str) -> "URL":
  1066. """Remove some keys from query part and return new URL."""
  1067. params_to_remove = set(query_params) & self.query.keys()
  1068. if not params_to_remove:
  1069. return self
  1070. return self.with_query(
  1071. tuple(
  1072. (name, value)
  1073. for name, value in self.query.items()
  1074. if name not in params_to_remove
  1075. )
  1076. )
  1077. def with_fragment(self, fragment: Union[str, None]) -> "URL":
  1078. """Return a new URL with fragment replaced.
  1079. Autoencode fragment if needed.
  1080. Clear fragment to default if None is passed.
  1081. """
  1082. # N.B. doesn't cleanup query/fragment
  1083. if fragment is None:
  1084. raw_fragment = ""
  1085. elif not isinstance(fragment, str):
  1086. raise TypeError("Invalid fragment type")
  1087. else:
  1088. raw_fragment = FRAGMENT_QUOTER(fragment)
  1089. if self._fragment == raw_fragment:
  1090. return self
  1091. return from_parts(
  1092. self._scheme, self._netloc, self._path, self._query, raw_fragment
  1093. )
  1094. def with_name(
  1095. self,
  1096. name: str,
  1097. *,
  1098. keep_query: bool = False,
  1099. keep_fragment: bool = False,
  1100. ) -> "URL":
  1101. """Return a new URL with name (last part of path) replaced.
  1102. Query and fragment parts are cleaned up.
  1103. Name is encoded if needed.
  1104. """
  1105. # N.B. DOES cleanup query/fragment
  1106. if not isinstance(name, str):
  1107. raise TypeError("Invalid name type")
  1108. if "/" in name:
  1109. raise ValueError("Slash in name is not allowed")
  1110. name = PATH_QUOTER(name)
  1111. if name in (".", ".."):
  1112. raise ValueError(". and .. values are forbidden")
  1113. parts = list(self.raw_parts)
  1114. if netloc := self._netloc:
  1115. if len(parts) == 1:
  1116. parts.append(name)
  1117. else:
  1118. parts[-1] = name
  1119. parts[0] = "" # replace leading '/'
  1120. else:
  1121. parts[-1] = name
  1122. if parts[0] == "/":
  1123. parts[0] = "" # replace leading '/'
  1124. query = self._query if keep_query else ""
  1125. fragment = self._fragment if keep_fragment else ""
  1126. return from_parts(self._scheme, netloc, "/".join(parts), query, fragment)
  1127. def with_suffix(
  1128. self,
  1129. suffix: str,
  1130. *,
  1131. keep_query: bool = False,
  1132. keep_fragment: bool = False,
  1133. ) -> "URL":
  1134. """Return a new URL with suffix (file extension of name) replaced.
  1135. Query and fragment parts are cleaned up.
  1136. suffix is encoded if needed.
  1137. """
  1138. if not isinstance(suffix, str):
  1139. raise TypeError("Invalid suffix type")
  1140. if suffix and not suffix[0] == "." or suffix == "." or "/" in suffix:
  1141. raise ValueError(f"Invalid suffix {suffix!r}")
  1142. name = self.raw_name
  1143. if not name:
  1144. raise ValueError(f"{self!r} has an empty name")
  1145. old_suffix = self.raw_suffix
  1146. suffix = PATH_QUOTER(suffix)
  1147. name = name + suffix if not old_suffix else name[: -len(old_suffix)] + suffix
  1148. if name in (".", ".."):
  1149. raise ValueError(". and .. values are forbidden")
  1150. parts = list(self.raw_parts)
  1151. if netloc := self._netloc:
  1152. if len(parts) == 1:
  1153. parts.append(name)
  1154. else:
  1155. parts[-1] = name
  1156. parts[0] = "" # replace leading '/'
  1157. else:
  1158. parts[-1] = name
  1159. if parts[0] == "/":
  1160. parts[0] = "" # replace leading '/'
  1161. query = self._query if keep_query else ""
  1162. fragment = self._fragment if keep_fragment else ""
  1163. return from_parts(self._scheme, netloc, "/".join(parts), query, fragment)
  1164. def join(self, url: "URL") -> "URL":
  1165. """Join URLs
  1166. Construct a full (“absolute”) URL by combining a “base URL”
  1167. (self) with another URL (url).
  1168. Informally, this uses components of the base URL, in
  1169. particular the addressing scheme, the network location and
  1170. (part of) the path, to provide missing components in the
  1171. relative URL.
  1172. """
  1173. if type(url) is not URL:
  1174. raise TypeError("url should be URL")
  1175. scheme = url._scheme or self._scheme
  1176. if scheme != self._scheme or scheme not in USES_RELATIVE:
  1177. return url
  1178. # scheme is in uses_authority as uses_authority is a superset of uses_relative
  1179. if (join_netloc := url._netloc) and scheme in USES_AUTHORITY:
  1180. return from_parts(scheme, join_netloc, url._path, url._query, url._fragment)
  1181. orig_path = self._path
  1182. if join_path := url._path:
  1183. if join_path[0] == "/":
  1184. path = join_path
  1185. elif not orig_path:
  1186. path = f"/{join_path}"
  1187. elif orig_path[-1] == "/":
  1188. path = f"{orig_path}{join_path}"
  1189. else:
  1190. # …
  1191. # and relativizing ".."
  1192. # parts[0] is / for absolute urls,
  1193. # this join will add a double slash there
  1194. path = "/".join([*self.parts[:-1], ""]) + join_path
  1195. # which has to be removed
  1196. if orig_path[0] == "/":
  1197. path = path[1:]
  1198. path = normalize_path(path) if "." in path else path
  1199. else:
  1200. path = orig_path
  1201. return from_parts(
  1202. scheme,
  1203. self._netloc,
  1204. path,
  1205. url._query if join_path or url._query else self._query,
  1206. url._fragment if join_path or url._fragment else self._fragment,
  1207. )
  1208. def joinpath(self, *other: str, encoded: bool = False) -> "URL":
  1209. """Return a new URL with the elements in other appended to the path."""
  1210. return self._make_child(other, encoded=encoded)
  1211. def human_repr(self) -> str:
  1212. """Return decoded human readable string for URL representation."""
  1213. user = human_quote(self.user, "#/:?@[]")
  1214. password = human_quote(self.password, "#/:?@[]")
  1215. if (host := self.host) and ":" in host:
  1216. host = f"[{host}]"
  1217. path = human_quote(self.path, "#?")
  1218. if TYPE_CHECKING:
  1219. assert path is not None
  1220. query_string = "&".join(
  1221. "{}={}".format(human_quote(k, "#&+;="), human_quote(v, "#&+;="))
  1222. for k, v in self.query.items()
  1223. )
  1224. fragment = human_quote(self.fragment, "")
  1225. if TYPE_CHECKING:
  1226. assert fragment is not None
  1227. netloc = make_netloc(user, password, host, self.explicit_port)
  1228. return unsplit_result(self._scheme, netloc, path, query_string, fragment)
  1229. _DEFAULT_IDNA_SIZE = 256
  1230. _DEFAULT_ENCODE_SIZE = 512
  1231. @lru_cache(_DEFAULT_IDNA_SIZE)
  1232. def _idna_decode(raw: str) -> str:
  1233. try:
  1234. return idna.decode(raw.encode("ascii"))
  1235. except UnicodeError: # e.g. '::1'
  1236. return raw.encode("ascii").decode("idna")
  1237. @lru_cache(_DEFAULT_IDNA_SIZE)
  1238. def _idna_encode(host: str) -> str:
  1239. try:
  1240. return idna.encode(host, uts46=True).decode("ascii")
  1241. except UnicodeError:
  1242. return host.encode("idna").decode("ascii")
  1243. @lru_cache(_DEFAULT_ENCODE_SIZE)
  1244. def _encode_host(host: str, validate_host: bool) -> str:
  1245. """Encode host part of URL."""
  1246. # If the host ends with a digit or contains a colon, its likely
  1247. # an IP address.
  1248. if host and (host[-1].isdigit() or ":" in host):
  1249. raw_ip, sep, zone = host.partition("%")
  1250. # If it looks like an IP, we check with _ip_compressed_version
  1251. # and fall-through if its not an IP address. This is a performance
  1252. # optimization to avoid parsing IP addresses as much as possible
  1253. # because it is orders of magnitude slower than almost any other
  1254. # operation this library does.
  1255. # Might be an IP address, check it
  1256. #
  1257. # IP Addresses can look like:
  1258. # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2
  1259. # - 127.0.0.1 (last character is a digit)
  1260. # - 2001:db8::ff00:42:8329 (contains a colon)
  1261. # - 2001:db8::ff00:42:8329%eth0 (contains a colon)
  1262. # - [2001:db8::ff00:42:8329] (contains a colon -- brackets should
  1263. # have been removed before it gets here)
  1264. # Rare IP Address formats are not supported per:
  1265. # https://datatracker.ietf.org/doc/html/rfc3986#section-7.4
  1266. #
  1267. # IP parsing is slow, so its wrapped in an LRU
  1268. try:
  1269. ip = ip_address(raw_ip)
  1270. except ValueError:
  1271. pass
  1272. else:
  1273. # These checks should not happen in the
  1274. # LRU to keep the cache size small
  1275. host = ip.compressed
  1276. if ip.version == 6:
  1277. return f"[{host}%{zone}]" if sep else f"[{host}]"
  1278. return f"{host}%{zone}" if sep else host
  1279. # IDNA encoding is slow, skip it for ASCII-only strings
  1280. if host.isascii():
  1281. # Check for invalid characters explicitly; _idna_encode() does this
  1282. # for non-ascii host names.
  1283. host = host.lower()
  1284. if validate_host and (invalid := NOT_REG_NAME.search(host)):
  1285. value, pos, extra = invalid.group(), invalid.start(), ""
  1286. if value == "@" or (value == ":" and "@" in host[pos:]):
  1287. # this looks like an authority string
  1288. extra = (
  1289. ", if the value includes a username or password, "
  1290. "use 'authority' instead of 'host'"
  1291. )
  1292. raise ValueError(
  1293. f"Host {host!r} cannot contain {value!r} (at position {pos}){extra}"
  1294. ) from None
  1295. return host
  1296. return _idna_encode(host)
  1297. @rewrite_module
  1298. def cache_clear() -> None:
  1299. """Clear all LRU caches."""
  1300. _idna_encode.cache_clear()
  1301. _idna_decode.cache_clear()
  1302. _encode_host.cache_clear()
  1303. @rewrite_module
  1304. def cache_info() -> CacheInfo:
  1305. """Report cache statistics."""
  1306. return {
  1307. "idna_encode": _idna_encode.cache_info(),
  1308. "idna_decode": _idna_decode.cache_info(),
  1309. "ip_address": _encode_host.cache_info(),
  1310. "host_validate": _encode_host.cache_info(),
  1311. "encode_host": _encode_host.cache_info(),
  1312. }
  1313. @rewrite_module
  1314. def cache_configure(
  1315. *,
  1316. idna_encode_size: Union[int, None] = _DEFAULT_IDNA_SIZE,
  1317. idna_decode_size: Union[int, None] = _DEFAULT_IDNA_SIZE,
  1318. ip_address_size: Union[int, None, UndefinedType] = UNDEFINED,
  1319. host_validate_size: Union[int, None, UndefinedType] = UNDEFINED,
  1320. encode_host_size: Union[int, None, UndefinedType] = UNDEFINED,
  1321. ) -> None:
  1322. """Configure LRU cache sizes."""
  1323. global _idna_decode, _idna_encode, _encode_host
  1324. # ip_address_size, host_validate_size are no longer
  1325. # used, but are kept for backwards compatibility.
  1326. if ip_address_size is not UNDEFINED or host_validate_size is not UNDEFINED:
  1327. warnings.warn(
  1328. "cache_configure() no longer accepts the "
  1329. "ip_address_size or host_validate_size arguments, "
  1330. "they are used to set the encode_host_size instead "
  1331. "and will be removed in the future",
  1332. DeprecationWarning,
  1333. stacklevel=2,
  1334. )
  1335. if encode_host_size is not None:
  1336. for size in (ip_address_size, host_validate_size):
  1337. if size is None:
  1338. encode_host_size = None
  1339. elif encode_host_size is UNDEFINED:
  1340. if size is not UNDEFINED:
  1341. encode_host_size = size
  1342. elif size is not UNDEFINED:
  1343. if TYPE_CHECKING:
  1344. assert isinstance(size, int)
  1345. assert isinstance(encode_host_size, int)
  1346. encode_host_size = max(size, encode_host_size)
  1347. if encode_host_size is UNDEFINED:
  1348. encode_host_size = _DEFAULT_ENCODE_SIZE
  1349. _encode_host = lru_cache(encode_host_size)(_encode_host.__wrapped__)
  1350. _idna_decode = lru_cache(idna_decode_size)(_idna_decode.__wrapped__)
  1351. _idna_encode = lru_cache(idna_encode_size)(_idna_encode.__wrapped__)