urls.py 37 KB

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