urls.py 38 KB

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