You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1007 lines
36 KiB

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