urls.py 36 KB

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