urls.py 36 KB

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