Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1135 Zeilen
38KB

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