urls.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. """Functions for working with URLs.
  2. Contains implementations of functions from :mod:`urllib.parse` that
  3. handle bytes and strings.
  4. """
  5. import codecs
  6. import os
  7. import re
  8. import typing as t
  9. import warnings
  10. from ._internal import _check_str_tuple
  11. from ._internal import _decode_idna
  12. from ._internal import _encode_idna
  13. from ._internal import _make_encode_wrapper
  14. from ._internal import _to_str
  15. if t.TYPE_CHECKING:
  16. from . import datastructures as ds
  17. # A regular expression for what a valid schema looks like
  18. _scheme_re = re.compile(r"^[a-zA-Z0-9+-.]+$")
  19. # Characters that are safe in any part of an URL.
  20. _always_safe = frozenset(
  21. bytearray(
  22. b"abcdefghijklmnopqrstuvwxyz"
  23. b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  24. b"0123456789"
  25. b"-._~"
  26. )
  27. )
  28. _hexdigits = "0123456789ABCDEFabcdef"
  29. _hextobyte = {
  30. f"{a}{b}".encode("ascii"): int(f"{a}{b}", 16)
  31. for a in _hexdigits
  32. for b in _hexdigits
  33. }
  34. _bytetohex = [f"%{char:02X}".encode("ascii") for char in range(256)]
  35. class _URLTuple(t.NamedTuple):
  36. scheme: str
  37. netloc: str
  38. path: str
  39. query: str
  40. fragment: str
  41. class BaseURL(_URLTuple):
  42. """Superclass of :py:class:`URL` and :py:class:`BytesURL`."""
  43. __slots__ = ()
  44. _at: str
  45. _colon: str
  46. _lbracket: str
  47. _rbracket: str
  48. def __str__(self) -> str:
  49. return self.to_url()
  50. def replace(self, **kwargs: t.Any) -> "BaseURL":
  51. """Return an URL with the same values, except for those parameters
  52. given new values by whichever keyword arguments are specified."""
  53. return self._replace(**kwargs)
  54. @property
  55. def host(self) -> t.Optional[str]:
  56. """The host part of the URL if available, otherwise `None`. The
  57. host is either the hostname or the IP address mentioned in the
  58. URL. It will not contain the port.
  59. """
  60. return self._split_host()[0]
  61. @property
  62. def ascii_host(self) -> t.Optional[str]:
  63. """Works exactly like :attr:`host` but will return a result that
  64. is restricted to ASCII. If it finds a netloc that is not ASCII
  65. it will attempt to idna decode it. This is useful for socket
  66. operations when the URL might include internationalized characters.
  67. """
  68. rv = self.host
  69. if rv is not None and isinstance(rv, str):
  70. try:
  71. rv = _encode_idna(rv) # type: ignore
  72. except UnicodeError:
  73. rv = rv.encode("ascii", "ignore") # type: ignore
  74. return _to_str(rv, "ascii", "ignore")
  75. @property
  76. def port(self) -> t.Optional[int]:
  77. """The port in the URL as an integer if it was present, `None`
  78. otherwise. This does not fill in default ports.
  79. """
  80. try:
  81. rv = int(_to_str(self._split_host()[1]))
  82. if 0 <= rv <= 65535:
  83. return rv
  84. except (ValueError, TypeError):
  85. pass
  86. return None
  87. @property
  88. def auth(self) -> t.Optional[str]:
  89. """The authentication part in the URL if available, `None`
  90. otherwise.
  91. """
  92. return self._split_netloc()[0]
  93. @property
  94. def username(self) -> t.Optional[str]:
  95. """The username if it was part of the URL, `None` otherwise.
  96. This undergoes URL decoding and will always be a string.
  97. """
  98. rv = self._split_auth()[0]
  99. if rv is not None:
  100. return _url_unquote_legacy(rv)
  101. return None
  102. @property
  103. def raw_username(self) -> t.Optional[str]:
  104. """The username if it was part of the URL, `None` otherwise.
  105. Unlike :attr:`username` this one is not being decoded.
  106. """
  107. return self._split_auth()[0]
  108. @property
  109. def password(self) -> t.Optional[str]:
  110. """The password if it was part of the URL, `None` otherwise.
  111. This undergoes URL decoding and will always be a string.
  112. """
  113. rv = self._split_auth()[1]
  114. if rv is not None:
  115. return _url_unquote_legacy(rv)
  116. return None
  117. @property
  118. def raw_password(self) -> t.Optional[str]:
  119. """The password if it was part of the URL, `None` otherwise.
  120. Unlike :attr:`password` this one is not being decoded.
  121. """
  122. return self._split_auth()[1]
  123. def decode_query(self, *args: t.Any, **kwargs: t.Any) -> "ds.MultiDict[str, str]":
  124. """Decodes the query part of the URL. Ths is a shortcut for
  125. calling :func:`url_decode` on the query argument. The arguments and
  126. keyword arguments are forwarded to :func:`url_decode` unchanged.
  127. """
  128. return url_decode(self.query, *args, **kwargs)
  129. def join(self, *args: t.Any, **kwargs: t.Any) -> "BaseURL":
  130. """Joins this URL with another one. This is just a convenience
  131. function for calling into :meth:`url_join` and then parsing the
  132. return value again.
  133. """
  134. return url_parse(url_join(self, *args, **kwargs))
  135. def to_url(self) -> str:
  136. """Returns a URL string or bytes depending on the type of the
  137. information stored. This is just a convenience function
  138. for calling :meth:`url_unparse` for this URL.
  139. """
  140. return url_unparse(self)
  141. def encode_netloc(self) -> str:
  142. """Encodes the netloc part to an ASCII safe URL as bytes."""
  143. rv = self.ascii_host or ""
  144. if ":" in rv:
  145. rv = f"[{rv}]"
  146. port = self.port
  147. if port is not None:
  148. rv = f"{rv}:{port}"
  149. auth = ":".join(
  150. filter(
  151. None,
  152. [
  153. url_quote(self.raw_username or "", "utf-8", "strict", "/:%"),
  154. url_quote(self.raw_password or "", "utf-8", "strict", "/:%"),
  155. ],
  156. )
  157. )
  158. if auth:
  159. rv = f"{auth}@{rv}"
  160. return rv
  161. def decode_netloc(self) -> str:
  162. """Decodes the netloc part into a string."""
  163. rv = _decode_idna(self.host or "")
  164. if ":" in rv:
  165. rv = f"[{rv}]"
  166. port = self.port
  167. if port is not None:
  168. rv = f"{rv}:{port}"
  169. auth = ":".join(
  170. filter(
  171. None,
  172. [
  173. _url_unquote_legacy(self.raw_username or "", "/:%@"),
  174. _url_unquote_legacy(self.raw_password or "", "/:%@"),
  175. ],
  176. )
  177. )
  178. if auth:
  179. rv = f"{auth}@{rv}"
  180. return rv
  181. def to_uri_tuple(self) -> "BaseURL":
  182. """Returns a :class:`BytesURL` tuple that holds a URI. This will
  183. encode all the information in the URL properly to ASCII using the
  184. rules a web browser would follow.
  185. It's usually more interesting to directly call :meth:`iri_to_uri` which
  186. will return a string.
  187. """
  188. return url_parse(iri_to_uri(self))
  189. def to_iri_tuple(self) -> "BaseURL":
  190. """Returns a :class:`URL` tuple that holds a IRI. This will try
  191. to decode as much information as possible in the URL without
  192. losing information similar to how a web browser does it for the
  193. URL bar.
  194. It's usually more interesting to directly call :meth:`uri_to_iri` which
  195. will return a string.
  196. """
  197. return url_parse(uri_to_iri(self))
  198. def get_file_location(
  199. self, pathformat: t.Optional[str] = None
  200. ) -> t.Tuple[t.Optional[str], t.Optional[str]]:
  201. """Returns a tuple with the location of the file in the form
  202. ``(server, location)``. If the netloc is empty in the URL or
  203. points to localhost, it's represented as ``None``.
  204. The `pathformat` by default is autodetection but needs to be set
  205. when working with URLs of a specific system. The supported values
  206. are ``'windows'`` when working with Windows or DOS paths and
  207. ``'posix'`` when working with posix paths.
  208. If the URL does not point to a local file, the server and location
  209. are both represented as ``None``.
  210. :param pathformat: The expected format of the path component.
  211. Currently ``'windows'`` and ``'posix'`` are
  212. supported. Defaults to ``None`` which is
  213. autodetect.
  214. """
  215. if self.scheme != "file":
  216. return None, None
  217. path = url_unquote(self.path)
  218. host = self.netloc or None
  219. if pathformat is None:
  220. if os.name == "nt":
  221. pathformat = "windows"
  222. else:
  223. pathformat = "posix"
  224. if pathformat == "windows":
  225. if path[:1] == "/" and path[1:2].isalpha() and path[2:3] in "|:":
  226. path = f"{path[1:2]}:{path[3:]}"
  227. windows_share = path[:3] in ("\\" * 3, "/" * 3)
  228. import ntpath
  229. path = ntpath.normpath(path)
  230. # Windows shared drives are represented as ``\\host\\directory``.
  231. # That results in a URL like ``file://///host/directory``, and a
  232. # path like ``///host/directory``. We need to special-case this
  233. # because the path contains the hostname.
  234. if windows_share and host is None:
  235. parts = path.lstrip("\\").split("\\", 1)
  236. if len(parts) == 2:
  237. host, path = parts
  238. else:
  239. host = parts[0]
  240. path = ""
  241. elif pathformat == "posix":
  242. import posixpath
  243. path = posixpath.normpath(path)
  244. else:
  245. raise TypeError(f"Invalid path format {pathformat!r}")
  246. if host in ("127.0.0.1", "::1", "localhost"):
  247. host = None
  248. return host, path
  249. def _split_netloc(self) -> t.Tuple[t.Optional[str], str]:
  250. if self._at in self.netloc:
  251. auth, _, netloc = self.netloc.partition(self._at)
  252. return auth, netloc
  253. return None, self.netloc
  254. def _split_auth(self) -> t.Tuple[t.Optional[str], t.Optional[str]]:
  255. auth = self._split_netloc()[0]
  256. if not auth:
  257. return None, None
  258. if self._colon not in auth:
  259. return auth, None
  260. username, _, password = auth.partition(self._colon)
  261. return username, password
  262. def _split_host(self) -> t.Tuple[t.Optional[str], t.Optional[str]]:
  263. rv = self._split_netloc()[1]
  264. if not rv:
  265. return None, None
  266. if not rv.startswith(self._lbracket):
  267. if self._colon in rv:
  268. host, _, port = rv.partition(self._colon)
  269. return host, port
  270. return rv, None
  271. idx = rv.find(self._rbracket)
  272. if idx < 0:
  273. return rv, None
  274. host = rv[1:idx]
  275. rest = rv[idx + 1 :]
  276. if rest.startswith(self._colon):
  277. return host, rest[1:]
  278. return host, None
  279. class URL(BaseURL):
  280. """Represents a parsed URL. This behaves like a regular tuple but
  281. also has some extra attributes that give further insight into the
  282. URL.
  283. """
  284. __slots__ = ()
  285. _at = "@"
  286. _colon = ":"
  287. _lbracket = "["
  288. _rbracket = "]"
  289. def encode(self, charset: str = "utf-8", errors: str = "replace") -> "BytesURL":
  290. """Encodes the URL to a tuple made out of bytes. The charset is
  291. only being used for the path, query and fragment.
  292. """
  293. return BytesURL(
  294. self.scheme.encode("ascii"), # type: ignore
  295. self.encode_netloc(),
  296. self.path.encode(charset, errors), # type: ignore
  297. self.query.encode(charset, errors), # type: ignore
  298. self.fragment.encode(charset, errors), # type: ignore
  299. )
  300. class BytesURL(BaseURL):
  301. """Represents a parsed URL in bytes."""
  302. __slots__ = ()
  303. _at = b"@" # type: ignore
  304. _colon = b":" # type: ignore
  305. _lbracket = b"[" # type: ignore
  306. _rbracket = b"]" # type: ignore
  307. def __str__(self) -> str:
  308. return self.to_url().decode("utf-8", "replace") # type: ignore
  309. def encode_netloc(self) -> bytes: # type: ignore
  310. """Returns the netloc unchanged as bytes."""
  311. return self.netloc # type: ignore
  312. def decode(self, charset: str = "utf-8", errors: str = "replace") -> "URL":
  313. """Decodes the URL to a tuple made out of strings. The charset is
  314. only being used for the path, query and fragment.
  315. """
  316. return URL(
  317. self.scheme.decode("ascii"), # type: ignore
  318. self.decode_netloc(),
  319. self.path.decode(charset, errors), # type: ignore
  320. self.query.decode(charset, errors), # type: ignore
  321. self.fragment.decode(charset, errors), # type: ignore
  322. )
  323. _unquote_maps: t.Dict[t.FrozenSet[int], t.Dict[bytes, int]] = {frozenset(): _hextobyte}
  324. def _unquote_to_bytes(
  325. string: t.Union[str, bytes], unsafe: t.Union[str, bytes] = ""
  326. ) -> bytes:
  327. if isinstance(string, str):
  328. string = string.encode("utf-8")
  329. if isinstance(unsafe, str):
  330. unsafe = unsafe.encode("utf-8")
  331. unsafe = frozenset(bytearray(unsafe))
  332. groups = iter(string.split(b"%"))
  333. result = bytearray(next(groups, b""))
  334. try:
  335. hex_to_byte = _unquote_maps[unsafe]
  336. except KeyError:
  337. hex_to_byte = _unquote_maps[unsafe] = {
  338. h: b for h, b in _hextobyte.items() if b not in unsafe
  339. }
  340. for group in groups:
  341. code = group[:2]
  342. if code in hex_to_byte:
  343. result.append(hex_to_byte[code])
  344. result.extend(group[2:])
  345. else:
  346. result.append(37) # %
  347. result.extend(group)
  348. return bytes(result)
  349. def _url_encode_impl(
  350. obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]],
  351. charset: str,
  352. sort: bool,
  353. key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]],
  354. ) -> t.Iterator[str]:
  355. from .datastructures import iter_multi_items
  356. iterable: t.Iterable[t.Tuple[str, str]] = iter_multi_items(obj)
  357. if sort:
  358. iterable = sorted(iterable, key=key)
  359. for key_str, value_str in iterable:
  360. if value_str is None:
  361. continue
  362. if not isinstance(key_str, bytes):
  363. key_bytes = str(key_str).encode(charset)
  364. else:
  365. key_bytes = key_str
  366. if not isinstance(value_str, bytes):
  367. value_bytes = str(value_str).encode(charset)
  368. else:
  369. value_bytes = value_str
  370. yield f"{_fast_url_quote_plus(key_bytes)}={_fast_url_quote_plus(value_bytes)}"
  371. def _url_unquote_legacy(value: str, unsafe: str = "") -> str:
  372. try:
  373. return url_unquote(value, charset="utf-8", errors="strict", unsafe=unsafe)
  374. except UnicodeError:
  375. return url_unquote(value, charset="latin1", unsafe=unsafe)
  376. def url_parse(
  377. url: str, scheme: t.Optional[str] = None, allow_fragments: bool = True
  378. ) -> BaseURL:
  379. """Parses a URL from a string into a :class:`URL` tuple. If the URL
  380. is lacking a scheme it can be provided as second argument. Otherwise,
  381. it is ignored. Optionally fragments can be stripped from the URL
  382. by setting `allow_fragments` to `False`.
  383. The inverse of this function is :func:`url_unparse`.
  384. :param url: the URL to parse.
  385. :param scheme: the default schema to use if the URL is schemaless.
  386. :param allow_fragments: if set to `False` a fragment will be removed
  387. from the URL.
  388. """
  389. s = _make_encode_wrapper(url)
  390. is_text_based = isinstance(url, str)
  391. if scheme is None:
  392. scheme = s("")
  393. netloc = query = fragment = s("")
  394. i = url.find(s(":"))
  395. if i > 0 and _scheme_re.match(_to_str(url[:i], errors="replace")):
  396. # make sure "iri" is not actually a port number (in which case
  397. # "scheme" is really part of the path)
  398. rest = url[i + 1 :]
  399. if not rest or any(c not in s("0123456789") for c in rest):
  400. # not a port number
  401. scheme, url = url[:i].lower(), rest
  402. if url[:2] == s("//"):
  403. delim = len(url)
  404. for c in s("/?#"):
  405. wdelim = url.find(c, 2)
  406. if wdelim >= 0:
  407. delim = min(delim, wdelim)
  408. netloc, url = url[2:delim], url[delim:]
  409. if (s("[") in netloc and s("]") not in netloc) or (
  410. s("]") in netloc and s("[") not in netloc
  411. ):
  412. raise ValueError("Invalid IPv6 URL")
  413. if allow_fragments and s("#") in url:
  414. url, fragment = url.split(s("#"), 1)
  415. if s("?") in url:
  416. url, query = url.split(s("?"), 1)
  417. result_type = URL if is_text_based else BytesURL
  418. return result_type(scheme, netloc, url, query, fragment)
  419. def _make_fast_url_quote(
  420. charset: str = "utf-8",
  421. errors: str = "strict",
  422. safe: t.Union[str, bytes] = "/:",
  423. unsafe: t.Union[str, bytes] = "",
  424. ) -> t.Callable[[bytes], str]:
  425. """Precompile the translation table for a URL encoding function.
  426. Unlike :func:`url_quote`, the generated function only takes the
  427. string to quote.
  428. :param charset: The charset to encode the result with.
  429. :param errors: How to handle encoding errors.
  430. :param safe: An optional sequence of safe characters to never encode.
  431. :param unsafe: An optional sequence of unsafe characters to always encode.
  432. """
  433. if isinstance(safe, str):
  434. safe = safe.encode(charset, errors)
  435. if isinstance(unsafe, str):
  436. unsafe = unsafe.encode(charset, errors)
  437. safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe))
  438. table = [chr(c) if c in safe else f"%{c:02X}" for c in range(256)]
  439. def quote(string: bytes) -> str:
  440. return "".join([table[c] for c in string])
  441. return quote
  442. _fast_url_quote = _make_fast_url_quote()
  443. _fast_quote_plus = _make_fast_url_quote(safe=" ", unsafe="+")
  444. def _fast_url_quote_plus(string: bytes) -> str:
  445. return _fast_quote_plus(string).replace(" ", "+")
  446. def url_quote(
  447. string: t.Union[str, bytes],
  448. charset: str = "utf-8",
  449. errors: str = "strict",
  450. safe: t.Union[str, bytes] = "/:",
  451. unsafe: t.Union[str, bytes] = "",
  452. ) -> str:
  453. """URL encode a single string with a given encoding.
  454. :param s: the string to quote.
  455. :param charset: the charset to be used.
  456. :param safe: an optional sequence of safe characters.
  457. :param unsafe: an optional sequence of unsafe characters.
  458. .. versionadded:: 0.9.2
  459. The `unsafe` parameter was added.
  460. """
  461. if not isinstance(string, (str, bytes, bytearray)):
  462. string = str(string)
  463. if isinstance(string, str):
  464. string = string.encode(charset, errors)
  465. if isinstance(safe, str):
  466. safe = safe.encode(charset, errors)
  467. if isinstance(unsafe, str):
  468. unsafe = unsafe.encode(charset, errors)
  469. safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe))
  470. rv = bytearray()
  471. for char in bytearray(string):
  472. if char in safe:
  473. rv.append(char)
  474. else:
  475. rv.extend(_bytetohex[char])
  476. return bytes(rv).decode(charset)
  477. def url_quote_plus(
  478. string: str, charset: str = "utf-8", errors: str = "strict", safe: str = ""
  479. ) -> str:
  480. """URL encode a single string with the given encoding and convert
  481. whitespace to "+".
  482. :param s: The string to quote.
  483. :param charset: The charset to be used.
  484. :param safe: An optional sequence of safe characters.
  485. """
  486. return url_quote(string, charset, errors, safe + " ", "+").replace(" ", "+")
  487. def url_unparse(components: t.Tuple[str, str, str, str, str]) -> str:
  488. """The reverse operation to :meth:`url_parse`. This accepts arbitrary
  489. as well as :class:`URL` tuples and returns a URL as a string.
  490. :param components: the parsed URL as tuple which should be converted
  491. into a URL string.
  492. """
  493. _check_str_tuple(components)
  494. scheme, netloc, path, query, fragment = components
  495. s = _make_encode_wrapper(scheme)
  496. url = s("")
  497. # We generally treat file:///x and file:/x the same which is also
  498. # what browsers seem to do. This also allows us to ignore a schema
  499. # register for netloc utilization or having to differentiate between
  500. # empty and missing netloc.
  501. if netloc or (scheme and path.startswith(s("/"))):
  502. if path and path[:1] != s("/"):
  503. path = s("/") + path
  504. url = s("//") + (netloc or s("")) + path
  505. elif path:
  506. url += path
  507. if scheme:
  508. url = scheme + s(":") + url
  509. if query:
  510. url = url + s("?") + query
  511. if fragment:
  512. url = url + s("#") + fragment
  513. return url
  514. def url_unquote(
  515. s: t.Union[str, bytes],
  516. charset: str = "utf-8",
  517. errors: str = "replace",
  518. unsafe: str = "",
  519. ) -> str:
  520. """URL decode a single string with a given encoding. If the charset
  521. is set to `None` no decoding is performed and raw bytes are
  522. returned.
  523. :param s: the string to unquote.
  524. :param charset: the charset of the query string. If set to `None`
  525. no decoding will take place.
  526. :param errors: the error handling for the charset decoding.
  527. """
  528. rv = _unquote_to_bytes(s, unsafe)
  529. if charset is None:
  530. return rv
  531. return rv.decode(charset, errors)
  532. def url_unquote_plus(
  533. s: t.Union[str, bytes], charset: str = "utf-8", errors: str = "replace"
  534. ) -> str:
  535. """URL decode a single string with the given `charset` and decode "+" to
  536. whitespace.
  537. Per default encoding errors are ignored. If you want a different behavior
  538. you can set `errors` to ``'replace'`` or ``'strict'``.
  539. :param s: The string to unquote.
  540. :param charset: the charset of the query string. If set to `None`
  541. no decoding will take place.
  542. :param errors: The error handling for the `charset` decoding.
  543. """
  544. if isinstance(s, str):
  545. s = s.replace("+", " ")
  546. else:
  547. s = s.replace(b"+", b" ")
  548. return url_unquote(s, charset, errors)
  549. def url_fix(s: str, charset: str = "utf-8") -> str:
  550. r"""Sometimes you get an URL by a user that just isn't a real URL because
  551. it contains unsafe characters like ' ' and so on. This function can fix
  552. some of the problems in a similar way browsers handle data entered by the
  553. user:
  554. >>> url_fix('http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
  555. 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
  556. :param s: the string with the URL to fix.
  557. :param charset: The target charset for the URL if the url was given
  558. as a string.
  559. """
  560. # First step is to switch to text processing and to convert
  561. # backslashes (which are invalid in URLs anyways) to slashes. This is
  562. # consistent with what Chrome does.
  563. s = _to_str(s, charset, "replace").replace("\\", "/")
  564. # For the specific case that we look like a malformed windows URL
  565. # we want to fix this up manually:
  566. if s.startswith("file://") and s[7:8].isalpha() and s[8:10] in (":/", "|/"):
  567. s = f"file:///{s[7:]}"
  568. url = url_parse(s)
  569. path = url_quote(url.path, charset, safe="/%+$!*'(),")
  570. qs = url_quote_plus(url.query, charset, safe=":&%=+$!*'(),")
  571. anchor = url_quote_plus(url.fragment, charset, safe=":&%=+$!*'(),")
  572. return url_unparse((url.scheme, url.encode_netloc(), path, qs, anchor))
  573. # not-unreserved characters remain quoted when unquoting to IRI
  574. _to_iri_unsafe = "".join([chr(c) for c in range(128) if c not in _always_safe])
  575. def _codec_error_url_quote(e: UnicodeError) -> t.Tuple[str, int]:
  576. """Used in :func:`uri_to_iri` after unquoting to re-quote any
  577. invalid bytes.
  578. """
  579. # the docs state that UnicodeError does have these attributes,
  580. # but mypy isn't picking them up
  581. out = _fast_url_quote(e.object[e.start : e.end]) # type: ignore
  582. return out, e.end # type: ignore
  583. codecs.register_error("werkzeug.url_quote", _codec_error_url_quote)
  584. def uri_to_iri(
  585. uri: t.Union[str, t.Tuple[str, str, str, str, str]],
  586. charset: str = "utf-8",
  587. errors: str = "werkzeug.url_quote",
  588. ) -> str:
  589. """Convert a URI to an IRI. All valid UTF-8 characters are unquoted,
  590. leaving all reserved and invalid characters quoted. If the URL has
  591. a domain, it is decoded from Punycode.
  592. >>> uri_to_iri("http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF")
  593. 'http://\\u2603.net/p\\xe5th?q=\\xe8ry%DF'
  594. :param uri: The URI to convert.
  595. :param charset: The encoding to encode unquoted bytes with.
  596. :param errors: Error handler to use during ``bytes.encode``. By
  597. default, invalid bytes are left quoted.
  598. .. versionchanged:: 0.15
  599. All reserved and invalid characters remain quoted. Previously,
  600. only some reserved characters were preserved, and invalid bytes
  601. were replaced instead of left quoted.
  602. .. versionadded:: 0.6
  603. """
  604. if isinstance(uri, tuple):
  605. uri = url_unparse(uri)
  606. uri = url_parse(_to_str(uri, charset))
  607. path = url_unquote(uri.path, charset, errors, _to_iri_unsafe)
  608. query = url_unquote(uri.query, charset, errors, _to_iri_unsafe)
  609. fragment = url_unquote(uri.fragment, charset, errors, _to_iri_unsafe)
  610. return url_unparse((uri.scheme, uri.decode_netloc(), path, query, fragment))
  611. # reserved characters remain unquoted when quoting to URI
  612. _to_uri_safe = ":/?#[]@!$&'()*+,;=%"
  613. def iri_to_uri(
  614. iri: t.Union[str, t.Tuple[str, str, str, str, str]],
  615. charset: str = "utf-8",
  616. errors: str = "strict",
  617. safe_conversion: bool = False,
  618. ) -> str:
  619. """Convert an IRI to a URI. All non-ASCII and unsafe characters are
  620. quoted. If the URL has a domain, it is encoded to Punycode.
  621. >>> iri_to_uri('http://\\u2603.net/p\\xe5th?q=\\xe8ry%DF')
  622. 'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF'
  623. :param iri: The IRI to convert.
  624. :param charset: The encoding of the IRI.
  625. :param errors: Error handler to use during ``bytes.encode``.
  626. :param safe_conversion: Return the URL unchanged if it only contains
  627. ASCII characters and no whitespace. See the explanation below.
  628. There is a general problem with IRI conversion with some protocols
  629. that are in violation of the URI specification. Consider the
  630. following two IRIs::
  631. magnet:?xt=uri:whatever
  632. itms-services://?action=download-manifest
  633. After parsing, we don't know if the scheme requires the ``//``,
  634. which is dropped if empty, but conveys different meanings in the
  635. final URL if it's present or not. In this case, you can use
  636. ``safe_conversion``, which will return the URL unchanged if it only
  637. contains ASCII characters and no whitespace. This can result in a
  638. URI with unquoted characters if it was not already quoted correctly,
  639. but preserves the URL's semantics. Werkzeug uses this for the
  640. ``Location`` header for redirects.
  641. .. versionchanged:: 0.15
  642. All reserved characters remain unquoted. Previously, only some
  643. reserved characters were left unquoted.
  644. .. versionchanged:: 0.9.6
  645. The ``safe_conversion`` parameter was added.
  646. .. versionadded:: 0.6
  647. """
  648. if isinstance(iri, tuple):
  649. iri = url_unparse(iri)
  650. if safe_conversion:
  651. # If we're not sure if it's safe to convert the URL, and it only
  652. # contains ASCII characters, return it unconverted.
  653. try:
  654. native_iri = _to_str(iri)
  655. ascii_iri = native_iri.encode("ascii")
  656. # Only return if it doesn't have whitespace. (Why?)
  657. if len(ascii_iri.split()) == 1:
  658. return native_iri
  659. except UnicodeError:
  660. pass
  661. iri = url_parse(_to_str(iri, charset, errors))
  662. path = url_quote(iri.path, charset, errors, _to_uri_safe)
  663. query = url_quote(iri.query, charset, errors, _to_uri_safe)
  664. fragment = url_quote(iri.fragment, charset, errors, _to_uri_safe)
  665. return url_unparse((iri.scheme, iri.encode_netloc(), path, query, fragment))
  666. def url_decode(
  667. s: t.AnyStr,
  668. charset: str = "utf-8",
  669. decode_keys: None = None,
  670. include_empty: bool = True,
  671. errors: str = "replace",
  672. separator: str = "&",
  673. cls: t.Optional[t.Type["ds.MultiDict"]] = None,
  674. ) -> "ds.MultiDict[str, str]":
  675. """Parse a query string and return it as a :class:`MultiDict`.
  676. :param s: The query string to parse.
  677. :param charset: Decode bytes to string with this charset. If not
  678. given, bytes are returned as-is.
  679. :param include_empty: Include keys with empty values in the dict.
  680. :param errors: Error handling behavior when decoding bytes.
  681. :param separator: Separator character between pairs.
  682. :param cls: Container to hold result instead of :class:`MultiDict`.
  683. .. versionchanged:: 2.0
  684. The ``decode_keys`` parameter is deprecated and will be removed
  685. in Werkzeug 2.1.
  686. .. versionchanged:: 0.5
  687. In previous versions ";" and "&" could be used for url decoding.
  688. Now only "&" is supported. If you want to use ";", a different
  689. ``separator`` can be provided.
  690. .. versionchanged:: 0.5
  691. The ``cls`` parameter was added.
  692. """
  693. if decode_keys is not None:
  694. warnings.warn(
  695. "'decode_keys' is deprecated and will be removed in Werkzeug 2.1.",
  696. DeprecationWarning,
  697. stacklevel=2,
  698. )
  699. if cls is None:
  700. from .datastructures import MultiDict # noqa: F811
  701. cls = MultiDict
  702. if isinstance(s, str) and not isinstance(separator, str):
  703. separator = separator.decode(charset or "ascii")
  704. elif isinstance(s, bytes) and not isinstance(separator, bytes):
  705. separator = separator.encode(charset or "ascii") # type: ignore
  706. return cls(
  707. _url_decode_impl(
  708. s.split(separator), charset, include_empty, errors # type: ignore
  709. )
  710. )
  711. def url_decode_stream(
  712. stream: t.IO[bytes],
  713. charset: str = "utf-8",
  714. decode_keys: None = None,
  715. include_empty: bool = True,
  716. errors: str = "replace",
  717. separator: bytes = b"&",
  718. cls: t.Optional[t.Type["ds.MultiDict"]] = None,
  719. limit: t.Optional[int] = None,
  720. return_iterator: bool = False,
  721. ) -> "ds.MultiDict[str, str]":
  722. """Works like :func:`url_decode` but decodes a stream. The behavior
  723. of stream and limit follows functions like
  724. :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is
  725. directly fed to the `cls` so you can consume the data while it's
  726. parsed.
  727. :param stream: a stream with the encoded querystring
  728. :param charset: the charset of the query string. If set to `None`
  729. no decoding will take place.
  730. :param include_empty: Set to `False` if you don't want empty values to
  731. appear in the dict.
  732. :param errors: the decoding error behavior.
  733. :param separator: the pair separator to be used, defaults to ``&``
  734. :param cls: an optional dict class to use. If this is not specified
  735. or `None` the default :class:`MultiDict` is used.
  736. :param limit: the content length of the URL data. Not necessary if
  737. a limited stream is provided.
  738. .. versionchanged:: 2.0
  739. The ``decode_keys`` and ``return_iterator`` parameters are
  740. deprecated and will be removed in Werkzeug 2.1.
  741. .. versionadded:: 0.8
  742. """
  743. from .wsgi import make_chunk_iter
  744. if decode_keys is not None:
  745. warnings.warn(
  746. "'decode_keys' is deprecated and will be removed in Werkzeug 2.1.",
  747. DeprecationWarning,
  748. stacklevel=2,
  749. )
  750. pair_iter = make_chunk_iter(stream, separator, limit)
  751. decoder = _url_decode_impl(pair_iter, charset, include_empty, errors)
  752. if return_iterator:
  753. warnings.warn(
  754. "'return_iterator' is deprecated and will be removed in Werkzeug 2.1.",
  755. DeprecationWarning,
  756. stacklevel=2,
  757. )
  758. return decoder # type: ignore
  759. if cls is None:
  760. from .datastructures import MultiDict # noqa: F811
  761. cls = MultiDict
  762. return cls(decoder)
  763. def _url_decode_impl(
  764. pair_iter: t.Iterable[t.AnyStr], charset: str, include_empty: bool, errors: str
  765. ) -> t.Iterator[t.Tuple[str, str]]:
  766. for pair in pair_iter:
  767. if not pair:
  768. continue
  769. s = _make_encode_wrapper(pair)
  770. equal = s("=")
  771. if equal in pair:
  772. key, value = pair.split(equal, 1)
  773. else:
  774. if not include_empty:
  775. continue
  776. key = pair
  777. value = s("")
  778. yield (
  779. url_unquote_plus(key, charset, errors),
  780. url_unquote_plus(value, charset, errors),
  781. )
  782. def url_encode(
  783. obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]],
  784. charset: str = "utf-8",
  785. encode_keys: None = None,
  786. sort: bool = False,
  787. key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None,
  788. separator: str = "&",
  789. ) -> str:
  790. """URL encode a dict/`MultiDict`. If a value is `None` it will not appear
  791. in the result string. Per default only values are encoded into the target
  792. charset strings.
  793. :param obj: the object to encode into a query string.
  794. :param charset: the charset of the query string.
  795. :param sort: set to `True` if you want parameters to be sorted by `key`.
  796. :param separator: the separator to be used for the pairs.
  797. :param key: an optional function to be used for sorting. For more details
  798. check out the :func:`sorted` documentation.
  799. .. versionchanged:: 2.0
  800. The ``encode_keys`` parameter is deprecated and will be removed
  801. in Werkzeug 2.1.
  802. .. versionchanged:: 0.5
  803. Added the ``sort``, ``key``, and ``separator`` parameters.
  804. """
  805. if encode_keys is not None:
  806. warnings.warn(
  807. "'encode_keys' is deprecated and will be removed in Werkzeug 2.1.",
  808. DeprecationWarning,
  809. stacklevel=2,
  810. )
  811. separator = _to_str(separator, "ascii")
  812. return separator.join(_url_encode_impl(obj, charset, sort, key))
  813. def url_encode_stream(
  814. obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]],
  815. stream: t.Optional[t.IO[str]] = None,
  816. charset: str = "utf-8",
  817. encode_keys: None = None,
  818. sort: bool = False,
  819. key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None,
  820. separator: str = "&",
  821. ) -> None:
  822. """Like :meth:`url_encode` but writes the results to a stream
  823. object. If the stream is `None` a generator over all encoded
  824. pairs is returned.
  825. :param obj: the object to encode into a query string.
  826. :param stream: a stream to write the encoded object into or `None` if
  827. an iterator over the encoded pairs should be returned. In
  828. that case the separator argument is ignored.
  829. :param charset: the charset of the query string.
  830. :param sort: set to `True` if you want parameters to be sorted by `key`.
  831. :param separator: the separator to be used for the pairs.
  832. :param key: an optional function to be used for sorting. For more details
  833. check out the :func:`sorted` documentation.
  834. .. versionchanged:: 2.0
  835. The ``encode_keys`` parameter is deprecated and will be removed
  836. in Werkzeug 2.1.
  837. .. versionadded:: 0.8
  838. """
  839. if encode_keys is not None:
  840. warnings.warn(
  841. "'encode_keys' is deprecated and will be removed in Werkzeug 2.1.",
  842. DeprecationWarning,
  843. stacklevel=2,
  844. )
  845. separator = _to_str(separator, "ascii")
  846. gen = _url_encode_impl(obj, charset, sort, key)
  847. if stream is None:
  848. return gen # type: ignore
  849. for idx, chunk in enumerate(gen):
  850. if idx:
  851. stream.write(separator)
  852. stream.write(chunk)
  853. return None
  854. def url_join(
  855. base: t.Union[str, t.Tuple[str, str, str, str, str]],
  856. url: t.Union[str, t.Tuple[str, str, str, str, str]],
  857. allow_fragments: bool = True,
  858. ) -> str:
  859. """Join a base URL and a possibly relative URL to form an absolute
  860. interpretation of the latter.
  861. :param base: the base URL for the join operation.
  862. :param url: the URL to join.
  863. :param allow_fragments: indicates whether fragments should be allowed.
  864. """
  865. if isinstance(base, tuple):
  866. base = url_unparse(base)
  867. if isinstance(url, tuple):
  868. url = url_unparse(url)
  869. _check_str_tuple((base, url))
  870. s = _make_encode_wrapper(base)
  871. if not base:
  872. return url
  873. if not url:
  874. return base
  875. bscheme, bnetloc, bpath, bquery, bfragment = url_parse(
  876. base, allow_fragments=allow_fragments
  877. )
  878. scheme, netloc, path, query, fragment = url_parse(url, bscheme, allow_fragments)
  879. if scheme != bscheme:
  880. return url
  881. if netloc:
  882. return url_unparse((scheme, netloc, path, query, fragment))
  883. netloc = bnetloc
  884. if path[:1] == s("/"):
  885. segments = path.split(s("/"))
  886. elif not path:
  887. segments = bpath.split(s("/"))
  888. if not query:
  889. query = bquery
  890. else:
  891. segments = bpath.split(s("/"))[:-1] + path.split(s("/"))
  892. # If the rightmost part is "./" we want to keep the slash but
  893. # remove the dot.
  894. if segments[-1] == s("."):
  895. segments[-1] = s("")
  896. # Resolve ".." and "."
  897. segments = [segment for segment in segments if segment != s(".")]
  898. while True:
  899. i = 1
  900. n = len(segments) - 1
  901. while i < n:
  902. if segments[i] == s("..") and segments[i - 1] not in (s(""), s("..")):
  903. del segments[i - 1 : i + 1]
  904. break
  905. i += 1
  906. else:
  907. break
  908. # Remove trailing ".." if the URL is absolute
  909. unwanted_marker = [s(""), s("..")]
  910. while segments[:2] == unwanted_marker:
  911. del segments[1]
  912. path = s("/").join(segments)
  913. return url_unparse((scheme, netloc, path, query, fragment))
  914. class Href:
  915. """Implements a callable that constructs URLs with the given base. The
  916. function can be called with any number of positional and keyword
  917. arguments which than are used to assemble the URL. Works with URLs
  918. and posix paths.
  919. Positional arguments are appended as individual segments to
  920. the path of the URL:
  921. >>> href = Href('/foo')
  922. >>> href('bar', 23)
  923. '/foo/bar/23'
  924. >>> href('foo', bar=23)
  925. '/foo/foo?bar=23'
  926. If any of the arguments (positional or keyword) evaluates to `None` it
  927. will be skipped. If no keyword arguments are given the last argument
  928. can be a :class:`dict` or :class:`MultiDict` (or any other dict subclass),
  929. otherwise the keyword arguments are used for the query parameters, cutting
  930. off the first trailing underscore of the parameter name:
  931. >>> href(is_=42)
  932. '/foo?is=42'
  933. >>> href({'foo': 'bar'})
  934. '/foo?foo=bar'
  935. Combining of both methods is not allowed:
  936. >>> href({'foo': 'bar'}, bar=42)
  937. Traceback (most recent call last):
  938. ...
  939. TypeError: keyword arguments and query-dicts can't be combined
  940. Accessing attributes on the href object creates a new href object with
  941. the attribute name as prefix:
  942. >>> bar_href = href.bar
  943. >>> bar_href("blub")
  944. '/foo/bar/blub'
  945. If `sort` is set to `True` the items are sorted by `key` or the default
  946. sorting algorithm:
  947. >>> href = Href("/", sort=True)
  948. >>> href(a=1, b=2, c=3)
  949. '/?a=1&b=2&c=3'
  950. .. deprecated:: 2.0
  951. Will be removed in Werkzeug 2.1. Use :mod:`werkzeug.routing`
  952. instead.
  953. .. versionadded:: 0.5
  954. `sort` and `key` were added.
  955. """
  956. def __init__( # type: ignore
  957. self, base="./", charset="utf-8", sort=False, key=None
  958. ):
  959. warnings.warn(
  960. "'Href' is deprecated and will be removed in Werkzeug 2.1."
  961. " Use 'werkzeug.routing' instead.",
  962. DeprecationWarning,
  963. stacklevel=2,
  964. )
  965. if not base:
  966. base = "./"
  967. self.base = base
  968. self.charset = charset
  969. self.sort = sort
  970. self.key = key
  971. def __getattr__(self, name): # type: ignore
  972. if name[:2] == "__":
  973. raise AttributeError(name)
  974. base = self.base
  975. if base[-1:] != "/":
  976. base += "/"
  977. return Href(url_join(base, name), self.charset, self.sort, self.key)
  978. def __call__(self, *path, **query): # type: ignore
  979. if path and isinstance(path[-1], dict):
  980. if query:
  981. raise TypeError("keyword arguments and query-dicts can't be combined")
  982. query, path = path[-1], path[:-1]
  983. elif query:
  984. query = {k[:-1] if k.endswith("_") else k: v for k, v in query.items()}
  985. path = "/".join(
  986. [
  987. _to_str(url_quote(x, self.charset), "ascii")
  988. for x in path
  989. if x is not None
  990. ]
  991. ).lstrip("/")
  992. rv = self.base
  993. if path:
  994. if not rv.endswith("/"):
  995. rv += "/"
  996. rv = url_join(rv, f"./{path}")
  997. if query:
  998. rv += "?" + _to_str(
  999. url_encode(query, self.charset, sort=self.sort, key=self.key), "ascii"
  1000. )
  1001. return rv