urls.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. b"$!'()*+,;" # RFC3986 sub-delims set, not including query string delimiters &=
  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. include_empty: bool = True,
  670. errors: str = "replace",
  671. separator: str = "&",
  672. cls: t.Optional[t.Type["ds.MultiDict"]] = None,
  673. ) -> "ds.MultiDict[str, str]":
  674. """Parse a query string and return it as a :class:`MultiDict`.
  675. :param s: The query string to parse.
  676. :param charset: Decode bytes to string with this charset. If not
  677. given, bytes are returned as-is.
  678. :param include_empty: Include keys with empty values in the dict.
  679. :param errors: Error handling behavior when decoding bytes.
  680. :param separator: Separator character between pairs.
  681. :param cls: Container to hold result instead of :class:`MultiDict`.
  682. .. versionchanged:: 2.0
  683. The ``decode_keys`` parameter is deprecated and will be removed
  684. in Werkzeug 2.1.
  685. .. versionchanged:: 0.5
  686. In previous versions ";" and "&" could be used for url decoding.
  687. Now only "&" is supported. If you want to use ";", a different
  688. ``separator`` can be provided.
  689. .. versionchanged:: 0.5
  690. The ``cls`` parameter was added.
  691. """
  692. if cls is None:
  693. from .datastructures import MultiDict # noqa: F811
  694. cls = MultiDict
  695. if isinstance(s, str) and not isinstance(separator, str):
  696. separator = separator.decode(charset or "ascii")
  697. elif isinstance(s, bytes) and not isinstance(separator, bytes):
  698. separator = separator.encode(charset or "ascii") # type: ignore
  699. return cls(
  700. _url_decode_impl(
  701. s.split(separator), charset, include_empty, errors # type: ignore
  702. )
  703. )
  704. def url_decode_stream(
  705. stream: t.IO[bytes],
  706. charset: str = "utf-8",
  707. include_empty: bool = True,
  708. errors: str = "replace",
  709. separator: bytes = b"&",
  710. cls: t.Optional[t.Type["ds.MultiDict"]] = None,
  711. limit: t.Optional[int] = None,
  712. ) -> "ds.MultiDict[str, str]":
  713. """Works like :func:`url_decode` but decodes a stream. The behavior
  714. of stream and limit follows functions like
  715. :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is
  716. directly fed to the `cls` so you can consume the data while it's
  717. parsed.
  718. :param stream: a stream with the encoded querystring
  719. :param charset: the charset of the query string. If set to `None`
  720. no decoding will take place.
  721. :param include_empty: Set to `False` if you don't want empty values to
  722. appear in the dict.
  723. :param errors: the decoding error behavior.
  724. :param separator: the pair separator to be used, defaults to ``&``
  725. :param cls: an optional dict class to use. If this is not specified
  726. or `None` the default :class:`MultiDict` is used.
  727. :param limit: the content length of the URL data. Not necessary if
  728. a limited stream is provided.
  729. .. versionchanged:: 2.0
  730. The ``decode_keys`` and ``return_iterator`` parameters are
  731. deprecated and will be removed in Werkzeug 2.1.
  732. .. versionadded:: 0.8
  733. """
  734. from .wsgi import make_chunk_iter
  735. pair_iter = make_chunk_iter(stream, separator, limit)
  736. decoder = _url_decode_impl(pair_iter, charset, include_empty, errors)
  737. if cls is None:
  738. from .datastructures import MultiDict # noqa: F811
  739. cls = MultiDict
  740. return cls(decoder)
  741. def _url_decode_impl(
  742. pair_iter: t.Iterable[t.AnyStr], charset: str, include_empty: bool, errors: str
  743. ) -> t.Iterator[t.Tuple[str, str]]:
  744. for pair in pair_iter:
  745. if not pair:
  746. continue
  747. s = _make_encode_wrapper(pair)
  748. equal = s("=")
  749. if equal in pair:
  750. key, value = pair.split(equal, 1)
  751. else:
  752. if not include_empty:
  753. continue
  754. key = pair
  755. value = s("")
  756. yield (
  757. url_unquote_plus(key, charset, errors),
  758. url_unquote_plus(value, charset, errors),
  759. )
  760. def url_encode(
  761. obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]],
  762. charset: str = "utf-8",
  763. sort: bool = False,
  764. key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None,
  765. separator: str = "&",
  766. ) -> str:
  767. """URL encode a dict/`MultiDict`. If a value is `None` it will not appear
  768. in the result string. Per default only values are encoded into the target
  769. charset strings.
  770. :param obj: the object to encode into a query string.
  771. :param charset: the charset of the query string.
  772. :param sort: set to `True` if you want parameters to be sorted by `key`.
  773. :param separator: the separator to be used for the pairs.
  774. :param key: an optional function to be used for sorting. For more details
  775. check out the :func:`sorted` documentation.
  776. .. versionchanged:: 2.0
  777. The ``encode_keys`` parameter is deprecated and will be removed
  778. in Werkzeug 2.1.
  779. .. versionchanged:: 0.5
  780. Added the ``sort``, ``key``, and ``separator`` parameters.
  781. """
  782. separator = _to_str(separator, "ascii")
  783. return separator.join(_url_encode_impl(obj, charset, sort, key))
  784. def url_encode_stream(
  785. obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]],
  786. stream: t.Optional[t.IO[str]] = None,
  787. charset: str = "utf-8",
  788. sort: bool = False,
  789. key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None,
  790. separator: str = "&",
  791. ) -> None:
  792. """Like :meth:`url_encode` but writes the results to a stream
  793. object. If the stream is `None` a generator over all encoded
  794. pairs is returned.
  795. :param obj: the object to encode into a query string.
  796. :param stream: a stream to write the encoded object into or `None` if
  797. an iterator over the encoded pairs should be returned. In
  798. that case the separator argument is ignored.
  799. :param charset: the charset of the query string.
  800. :param sort: set to `True` if you want parameters to be sorted by `key`.
  801. :param separator: the separator to be used for the pairs.
  802. :param key: an optional function to be used for sorting. For more details
  803. check out the :func:`sorted` documentation.
  804. .. versionchanged:: 2.0
  805. The ``encode_keys`` parameter is deprecated and will be removed
  806. in Werkzeug 2.1.
  807. .. versionadded:: 0.8
  808. """
  809. separator = _to_str(separator, "ascii")
  810. gen = _url_encode_impl(obj, charset, sort, key)
  811. if stream is None:
  812. return gen # type: ignore
  813. for idx, chunk in enumerate(gen):
  814. if idx:
  815. stream.write(separator)
  816. stream.write(chunk)
  817. return None
  818. def url_join(
  819. base: t.Union[str, t.Tuple[str, str, str, str, str]],
  820. url: t.Union[str, t.Tuple[str, str, str, str, str]],
  821. allow_fragments: bool = True,
  822. ) -> str:
  823. """Join a base URL and a possibly relative URL to form an absolute
  824. interpretation of the latter.
  825. :param base: the base URL for the join operation.
  826. :param url: the URL to join.
  827. :param allow_fragments: indicates whether fragments should be allowed.
  828. """
  829. if isinstance(base, tuple):
  830. base = url_unparse(base)
  831. if isinstance(url, tuple):
  832. url = url_unparse(url)
  833. _check_str_tuple((base, url))
  834. s = _make_encode_wrapper(base)
  835. if not base:
  836. return url
  837. if not url:
  838. return base
  839. bscheme, bnetloc, bpath, bquery, bfragment = url_parse(
  840. base, allow_fragments=allow_fragments
  841. )
  842. scheme, netloc, path, query, fragment = url_parse(url, bscheme, allow_fragments)
  843. if scheme != bscheme:
  844. return url
  845. if netloc:
  846. return url_unparse((scheme, netloc, path, query, fragment))
  847. netloc = bnetloc
  848. if path[:1] == s("/"):
  849. segments = path.split(s("/"))
  850. elif not path:
  851. segments = bpath.split(s("/"))
  852. if not query:
  853. query = bquery
  854. else:
  855. segments = bpath.split(s("/"))[:-1] + path.split(s("/"))
  856. # If the rightmost part is "./" we want to keep the slash but
  857. # remove the dot.
  858. if segments[-1] == s("."):
  859. segments[-1] = s("")
  860. # Resolve ".." and "."
  861. segments = [segment for segment in segments if segment != s(".")]
  862. while True:
  863. i = 1
  864. n = len(segments) - 1
  865. while i < n:
  866. if segments[i] == s("..") and segments[i - 1] not in (s(""), s("..")):
  867. del segments[i - 1 : i + 1]
  868. break
  869. i += 1
  870. else:
  871. break
  872. # Remove trailing ".." if the URL is absolute
  873. unwanted_marker = [s(""), s("..")]
  874. while segments[:2] == unwanted_marker:
  875. del segments[1]
  876. path = s("/").join(segments)
  877. return url_unparse((scheme, netloc, path, query, fragment))