Guest User

Untitled

a guest
Apr 22nd, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 92.40 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.datastructures
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5.  
  6. This module provides mixins and classes with an immutable interface.
  7.  
  8. :copyright: 2007 Pallets
  9. :license: BSD-3-Clause
  10. """
  11. import codecs
  12. import mimetypes
  13. import re
  14. from copy import deepcopy
  15. from itertools import repeat
  16.  
  17. from ._compat import BytesIO
  18. from ._compat import collections_abc
  19. from ._compat import integer_types
  20. from ._compat import iteritems
  21. from ._compat import iterkeys
  22. from ._compat import iterlists
  23. from ._compat import itervalues
  24. from ._compat import make_literal_wrapper
  25. from ._compat import PY2
  26. from ._compat import string_types
  27. from ._compat import text_type
  28. from ._compat import to_native
  29. from ._internal import _missing
  30. from .filesystem import get_filesystem_encoding
  31.  
  32. _locale_delim_re = re.compile(r"[_-]")
  33.  
  34.  
  35. def is_immutable(self):
  36. raise TypeError("%r objects are immutable" % self.__class__.__name__)
  37.  
  38.  
  39. def iter_multi_items(mapping):
  40. """Iterates over the items of a mapping yielding keys and values
  41. without dropping any from more complex structures.
  42. """
  43. if isinstance(mapping, MultiDict):
  44. for item in iteritems(mapping, multi=True):
  45. yield item
  46. elif isinstance(mapping, dict):
  47. for key, value in iteritems(mapping):
  48. if isinstance(value, (tuple, list)):
  49. for value in value:
  50. yield key, value
  51. else:
  52. yield key, value
  53. else:
  54. for item in mapping:
  55. yield item
  56.  
  57.  
  58. def native_itermethods(names):
  59. if not PY2:
  60. return lambda x: x
  61.  
  62. def setviewmethod(cls, name):
  63. viewmethod_name = "view%s" % name
  64. repr_name = "view_%s" % name
  65.  
  66. def viewmethod(self, *a, **kw):
  67. return ViewItems(self, name, repr_name, *a, **kw)
  68.  
  69. viewmethod.__name__ = viewmethod_name
  70. viewmethod.__doc__ = "`%s()` object providing a view on %s" % (
  71. viewmethod_name,
  72. name,
  73. )
  74. setattr(cls, viewmethod_name, viewmethod)
  75.  
  76. def setitermethod(cls, name):
  77. itermethod = getattr(cls, name)
  78. setattr(cls, "iter%s" % name, itermethod)
  79.  
  80. def listmethod(self, *a, **kw):
  81. return list(itermethod(self, *a, **kw))
  82.  
  83. listmethod.__name__ = name
  84. listmethod.__doc__ = "Like :py:meth:`iter%s`, but returns a list." % name
  85. setattr(cls, name, listmethod)
  86.  
  87. def wrap(cls):
  88. for name in names:
  89. setitermethod(cls, name)
  90. setviewmethod(cls, name)
  91. return cls
  92.  
  93. return wrap
  94.  
  95.  
  96. class ImmutableListMixin(object):
  97. """Makes a :class:`list` immutable.
  98.  
  99. .. versionadded:: 0.5
  100.  
  101. :private:
  102. """
  103.  
  104. _hash_cache = None
  105.  
  106. def __hash__(self):
  107. if self._hash_cache is not None:
  108. return self._hash_cache
  109. rv = self._hash_cache = hash(tuple(self))
  110. return rv
  111.  
  112. def __reduce_ex__(self, protocol):
  113. return type(self), (list(self),)
  114.  
  115. def __delitem__(self, key):
  116. is_immutable(self)
  117.  
  118. def __iadd__(self, other):
  119. is_immutable(self)
  120.  
  121. __imul__ = __iadd__
  122.  
  123. def __setitem__(self, key, value):
  124. is_immutable(self)
  125.  
  126. def append(self, item):
  127. is_immutable(self)
  128.  
  129. remove = append
  130.  
  131. def extend(self, iterable):
  132. is_immutable(self)
  133.  
  134. def insert(self, pos, value):
  135. is_immutable(self)
  136.  
  137. def pop(self, index=-1):
  138. is_immutable(self)
  139.  
  140. def reverse(self):
  141. is_immutable(self)
  142.  
  143. def sort(self, cmp=None, key=None, reverse=None):
  144. is_immutable(self)
  145.  
  146.  
  147. class ImmutableList(ImmutableListMixin, list):
  148. """An immutable :class:`list`.
  149.  
  150. .. versionadded:: 0.5
  151.  
  152. :private:
  153. """
  154.  
  155. def __repr__(self):
  156. return "%s(%s)" % (self.__class__.__name__, list.__repr__(self))
  157.  
  158.  
  159. class ImmutableDictMixin(object):
  160. """Makes a :class:`dict` immutable.
  161.  
  162. .. versionadded:: 0.5
  163.  
  164. :private:
  165. """
  166.  
  167. _hash_cache = None
  168.  
  169. @classmethod
  170. def fromkeys(cls, keys, value=None):
  171. instance = super(cls, cls).__new__(cls)
  172. instance.__init__(zip(keys, repeat(value)))
  173. return instance
  174.  
  175. def __reduce_ex__(self, protocol):
  176. return type(self), (dict(self),)
  177.  
  178. def _iter_hashitems(self):
  179. return iteritems(self)
  180.  
  181. def __hash__(self):
  182. if self._hash_cache is not None:
  183. return self._hash_cache
  184. rv = self._hash_cache = hash(frozenset(self._iter_hashitems()))
  185. return rv
  186.  
  187. def setdefault(self, key, default=None):
  188. is_immutable(self)
  189.  
  190. def update(self, *args, **kwargs):
  191. is_immutable(self)
  192.  
  193. def pop(self, key, default=None):
  194. is_immutable(self)
  195.  
  196. def popitem(self):
  197. is_immutable(self)
  198.  
  199. def __setitem__(self, key, value):
  200. is_immutable(self)
  201.  
  202. def __delitem__(self, key):
  203. is_immutable(self)
  204.  
  205. def clear(self):
  206. is_immutable(self)
  207.  
  208.  
  209. class ImmutableMultiDictMixin(ImmutableDictMixin):
  210. """Makes a :class:`MultiDict` immutable.
  211.  
  212. .. versionadded:: 0.5
  213.  
  214. :private:
  215. """
  216.  
  217. def __reduce_ex__(self, protocol):
  218. return type(self), (list(iteritems(self, multi=True)),)
  219.  
  220. def _iter_hashitems(self):
  221. return iteritems(self, multi=True)
  222.  
  223. def add(self, key, value):
  224. is_immutable(self)
  225.  
  226. def popitemlist(self):
  227. is_immutable(self)
  228.  
  229. def poplist(self, key):
  230. is_immutable(self)
  231.  
  232. def setlist(self, key, new_list):
  233. is_immutable(self)
  234.  
  235. def setlistdefault(self, key, default_list=None):
  236. is_immutable(self)
  237.  
  238.  
  239. class UpdateDictMixin(object):
  240. """Makes dicts call `self.on_update` on modifications.
  241.  
  242. .. versionadded:: 0.5
  243.  
  244. :private:
  245. """
  246.  
  247. on_update = None
  248.  
  249. def calls_update(name): # noqa: B902
  250. def oncall(self, *args, **kw):
  251. rv = getattr(super(UpdateDictMixin, self), name)(*args, **kw)
  252. if self.on_update is not None:
  253. self.on_update(self)
  254. return rv
  255.  
  256. oncall.__name__ = name
  257. return oncall
  258.  
  259. def setdefault(self, key, default=None):
  260. modified = key not in self
  261. rv = super(UpdateDictMixin, self).setdefault(key, default)
  262. if modified and self.on_update is not None:
  263. self.on_update(self)
  264. return rv
  265.  
  266. def pop(self, key, default=_missing):
  267. modified = key in self
  268. if default is _missing:
  269. rv = super(UpdateDictMixin, self).pop(key)
  270. else:
  271. rv = super(UpdateDictMixin, self).pop(key, default)
  272. if modified and self.on_update is not None:
  273. self.on_update(self)
  274. return rv
  275.  
  276. __setitem__ = calls_update("__setitem__")
  277. __delitem__ = calls_update("__delitem__")
  278. clear = calls_update("clear")
  279. popitem = calls_update("popitem")
  280. update = calls_update("update")
  281. del calls_update
  282.  
  283.  
  284. class TypeConversionDict(dict):
  285. """Works like a regular dict but the :meth:`get` method can perform
  286. type conversions. :class:`MultiDict` and :class:`CombinedMultiDict`
  287. are subclasses of this class and provide the same feature.
  288.  
  289. .. versionadded:: 0.5
  290. """
  291.  
  292. def get(self, key, default=None, type=None):
  293. """Return the default value if the requested data doesn't exist.
  294. If `type` is provided and is a callable it should convert the value,
  295. return it or raise a :exc:`ValueError` if that is not possible. In
  296. this case the function will return the default as if the value was not
  297. found:
  298.  
  299. >>> d = TypeConversionDict(foo='42', bar='blub')
  300. >>> d.get('foo', type=int)
  301. 42
  302. >>> d.get('bar', -1, type=int)
  303. -1
  304.  
  305. :param key: The key to be looked up.
  306. :param default: The default value to be returned if the key can't
  307. be looked up. If not further specified `None` is
  308. returned.
  309. :param type: A callable that is used to cast the value in the
  310. :class:`MultiDict`. If a :exc:`ValueError` is raised
  311. by this callable the default value is returned.
  312. """
  313. try:
  314. rv = self[key]
  315. except KeyError:
  316. return default
  317. if type is not None:
  318. try:
  319. rv = type(rv)
  320. except ValueError:
  321. rv = default
  322. return rv
  323.  
  324.  
  325. class ImmutableTypeConversionDict(ImmutableDictMixin, TypeConversionDict):
  326. """Works like a :class:`TypeConversionDict` but does not support
  327. modifications.
  328.  
  329. .. versionadded:: 0.5
  330. """
  331.  
  332. def copy(self):
  333. """Return a shallow mutable copy of this object. Keep in mind that
  334. the standard library's :func:`copy` function is a no-op for this class
  335. like for any other python immutable type (eg: :class:`tuple`).
  336. """
  337. return TypeConversionDict(self)
  338.  
  339. def __copy__(self):
  340. return self
  341.  
  342.  
  343. class ViewItems(object):
  344. def __init__(self, multi_dict, method, repr_name, *a, **kw):
  345. self.__multi_dict = multi_dict
  346. self.__method = method
  347. self.__repr_name = repr_name
  348. self.__a = a
  349. self.__kw = kw
  350.  
  351. def __get_items(self):
  352. return getattr(self.__multi_dict, self.__method)(*self.__a, **self.__kw)
  353.  
  354. def __repr__(self):
  355. return "%s(%r)" % (self.__repr_name, list(self.__get_items()))
  356.  
  357. def __iter__(self):
  358. return iter(self.__get_items())
  359.  
  360.  
  361. @native_itermethods(["keys", "values", "items", "lists", "listvalues"])
  362. class MultiDict(TypeConversionDict):
  363. """A :class:`MultiDict` is a dictionary subclass customized to deal with
  364. multiple values for the same key which is for example used by the parsing
  365. functions in the wrappers. This is necessary because some HTML form
  366. elements pass multiple values for the same key.
  367.  
  368. :class:`MultiDict` implements all standard dictionary methods.
  369. Internally, it saves all values for a key as a list, but the standard dict
  370. access methods will only return the first value for a key. If you want to
  371. gain access to the other values, too, you have to use the `list` methods as
  372. explained below.
  373.  
  374. Basic Usage:
  375.  
  376. >>> d = MultiDict([('a', 'b'), ('a', 'c')])
  377. >>> d
  378. MultiDict([('a', 'b'), ('a', 'c')])
  379. >>> d['a']
  380. 'b'
  381. >>> d.getlist('a')
  382. ['b', 'c']
  383. >>> 'a' in d
  384. True
  385.  
  386. It behaves like a normal dict thus all dict functions will only return the
  387. first value when multiple values for one key are found.
  388.  
  389. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
  390. subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
  391. render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP
  392. exceptions.
  393.  
  394. A :class:`MultiDict` can be constructed from an iterable of
  395. ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2
  396. onwards some keyword parameters.
  397.  
  398. :param mapping: the initial value for the :class:`MultiDict`. Either a
  399. regular dict, an iterable of ``(key, value)`` tuples
  400. or `None`.
  401. """
  402.  
  403. def __init__(self, mapping=None):
  404. if isinstance(mapping, MultiDict):
  405. dict.__init__(self, ((k, l[:]) for k, l in iterlists(mapping)))
  406. elif isinstance(mapping, dict):
  407. tmp = {}
  408. for key, value in iteritems(mapping):
  409. if isinstance(value, (tuple, list)):
  410. if len(value) == 0:
  411. continue
  412. value = list(value)
  413. else:
  414. value = [value]
  415. tmp[key] = value
  416. dict.__init__(self, tmp)
  417. else:
  418. tmp = {}
  419. for key, value in mapping or ():
  420. tmp.setdefault(key, []).append(value)
  421. dict.__init__(self, tmp)
  422.  
  423. def __getstate__(self):
  424. return dict(self.lists())
  425.  
  426. def __setstate__(self, value):
  427. dict.clear(self)
  428. dict.update(self, value)
  429.  
  430. def __getitem__(self, key):
  431. """Return the first data value for this key;
  432. raises KeyError if not found.
  433.  
  434. :param key: The key to be looked up.
  435. :raise KeyError: if the key does not exist.
  436. """
  437.  
  438. if key in self:
  439. lst = dict.__getitem__(self, key)
  440. if len(lst) > 0:
  441. return lst[0]
  442. raise exceptions.BadRequestKeyError(key)
  443.  
  444. def __setitem__(self, key, value):
  445. """Like :meth:`add` but removes an existing key first.
  446.  
  447. :param key: the key for the value.
  448. :param value: the value to set.
  449. """
  450. dict.__setitem__(self, key, [value])
  451.  
  452. def add(self, key, value):
  453. """Adds a new value for the key.
  454.  
  455. .. versionadded:: 0.6
  456.  
  457. :param key: the key for the value.
  458. :param value: the value to add.
  459. """
  460. dict.setdefault(self, key, []).append(value)
  461.  
  462. def getlist(self, key, type=None):
  463. """Return the list of items for a given key. If that key is not in the
  464. `MultiDict`, the return value will be an empty list. Just as `get`
  465. `getlist` accepts a `type` parameter. All items will be converted
  466. with the callable defined there.
  467.  
  468. :param key: The key to be looked up.
  469. :param type: A callable that is used to cast the value in the
  470. :class:`MultiDict`. If a :exc:`ValueError` is raised
  471. by this callable the value will be removed from the list.
  472. :return: a :class:`list` of all the values for the key.
  473. """
  474. try:
  475. rv = dict.__getitem__(self, key)
  476. except KeyError:
  477. return []
  478. if type is None:
  479. return list(rv)
  480. result = []
  481. for item in rv:
  482. try:
  483. result.append(type(item))
  484. except ValueError:
  485. pass
  486. return result
  487.  
  488. def setlist(self, key, new_list):
  489. """Remove the old values for a key and add new ones. Note that the list
  490. you pass the values in will be shallow-copied before it is inserted in
  491. the dictionary.
  492.  
  493. >>> d = MultiDict()
  494. >>> d.setlist('foo', ['1', '2'])
  495. >>> d['foo']
  496. '1'
  497. >>> d.getlist('foo')
  498. ['1', '2']
  499.  
  500. :param key: The key for which the values are set.
  501. :param new_list: An iterable with the new values for the key. Old values
  502. are removed first.
  503. """
  504. dict.__setitem__(self, key, list(new_list))
  505.  
  506. def setdefault(self, key, default=None):
  507. """Returns the value for the key if it is in the dict, otherwise it
  508. returns `default` and sets that value for `key`.
  509.  
  510. :param key: The key to be looked up.
  511. :param default: The default value to be returned if the key is not
  512. in the dict. If not further specified it's `None`.
  513. """
  514. if key not in self:
  515. self[key] = default
  516. else:
  517. default = self[key]
  518. return default
  519.  
  520. def setlistdefault(self, key, default_list=None):
  521. """Like `setdefault` but sets multiple values. The list returned
  522. is not a copy, but the list that is actually used internally. This
  523. means that you can put new values into the dict by appending items
  524. to the list:
  525.  
  526. >>> d = MultiDict({"foo": 1})
  527. >>> d.setlistdefault("foo").extend([2, 3])
  528. >>> d.getlist("foo")
  529. [1, 2, 3]
  530.  
  531. :param key: The key to be looked up.
  532. :param default_list: An iterable of default values. It is either copied
  533. (in case it was a list) or converted into a list
  534. before returned.
  535. :return: a :class:`list`
  536. """
  537. if key not in self:
  538. default_list = list(default_list or ())
  539. dict.__setitem__(self, key, default_list)
  540. else:
  541. default_list = dict.__getitem__(self, key)
  542. return default_list
  543.  
  544. def items(self, multi=False):
  545. """Return an iterator of ``(key, value)`` pairs.
  546.  
  547. :param multi: If set to `True` the iterator returned will have a pair
  548. for each value of each key. Otherwise it will only
  549. contain pairs for the first value of each key.
  550. """
  551.  
  552. for key, values in iteritems(dict, self):
  553. if multi:
  554. for value in values:
  555. yield key, value
  556. else:
  557. yield key, values[0]
  558.  
  559. def lists(self):
  560. """Return a iterator of ``(key, values)`` pairs, where values is the list
  561. of all values associated with the key."""
  562.  
  563. for key, values in iteritems(dict, self):
  564. yield key, list(values)
  565.  
  566. def keys(self):
  567. return iterkeys(dict, self)
  568.  
  569. __iter__ = keys
  570.  
  571. def values(self):
  572. """Returns an iterator of the first value on every key's value list."""
  573. for values in itervalues(dict, self):
  574. yield values[0]
  575.  
  576. def listvalues(self):
  577. """Return an iterator of all values associated with a key. Zipping
  578. :meth:`keys` and this is the same as calling :meth:`lists`:
  579.  
  580. >>> d = MultiDict({"foo": [1, 2, 3]})
  581. >>> zip(d.keys(), d.listvalues()) == d.lists()
  582. True
  583. """
  584.  
  585. return itervalues(dict, self)
  586.  
  587. def copy(self):
  588. """Return a shallow copy of this object."""
  589. return self.__class__(self)
  590.  
  591. def deepcopy(self, memo=None):
  592. """Return a deep copy of this object."""
  593. return self.__class__(deepcopy(self.to_dict(flat=False), memo))
  594.  
  595. def to_dict(self, flat=True):
  596. """Return the contents as regular dict. If `flat` is `True` the
  597. returned dict will only have the first item present, if `flat` is
  598. `False` all values will be returned as lists.
  599.  
  600. :param flat: If set to `False` the dict returned will have lists
  601. with all the values in it. Otherwise it will only
  602. contain the first value for each key.
  603. :return: a :class:`dict`
  604. """
  605. if flat:
  606. return dict(iteritems(self))
  607. return dict(self.lists())
  608.  
  609. def update(self, other_dict):
  610. """update() extends rather than replaces existing key lists:
  611.  
  612. >>> a = MultiDict({'x': 1})
  613. >>> b = MultiDict({'x': 2, 'y': 3})
  614. >>> a.update(b)
  615. >>> a
  616. MultiDict([('y', 3), ('x', 1), ('x', 2)])
  617.  
  618. If the value list for a key in ``other_dict`` is empty, no new values
  619. will be added to the dict and the key will not be created:
  620.  
  621. >>> x = {'empty_list': []}
  622. >>> y = MultiDict()
  623. >>> y.update(x)
  624. >>> y
  625. MultiDict([])
  626. """
  627. for key, value in iter_multi_items(other_dict):
  628. MultiDict.add(self, key, value)
  629.  
  630. def pop(self, key, default=_missing):
  631. """Pop the first item for a list on the dict. Afterwards the
  632. key is removed from the dict, so additional values are discarded:
  633.  
  634. >>> d = MultiDict({"foo": [1, 2, 3]})
  635. >>> d.pop("foo")
  636. 1
  637. >>> "foo" in d
  638. False
  639.  
  640. :param key: the key to pop.
  641. :param default: if provided the value to return if the key was
  642. not in the dictionary.
  643. """
  644. try:
  645. lst = dict.pop(self, key)
  646.  
  647. if len(lst) == 0:
  648. raise exceptions.BadRequestKeyError(key)
  649.  
  650. return lst[0]
  651. except KeyError:
  652. if default is not _missing:
  653. return default
  654. raise exceptions.BadRequestKeyError(key)
  655.  
  656. def popitem(self):
  657. """Pop an item from the dict."""
  658. try:
  659. item = dict.popitem(self)
  660.  
  661. if len(item[1]) == 0:
  662. raise exceptions.BadRequestKeyError(item)
  663.  
  664. return (item[0], item[1][0])
  665. except KeyError as e:
  666. raise exceptions.BadRequestKeyError(e.args[0])
  667.  
  668. def poplist(self, key):
  669. """Pop the list for a key from the dict. If the key is not in the dict
  670. an empty list is returned.
  671.  
  672. .. versionchanged:: 0.5
  673. If the key does no longer exist a list is returned instead of
  674. raising an error.
  675. """
  676. return dict.pop(self, key, [])
  677.  
  678. def popitemlist(self):
  679. """Pop a ``(key, list)`` tuple from the dict."""
  680. try:
  681. return dict.popitem(self)
  682. except KeyError as e:
  683. raise exceptions.BadRequestKeyError(e.args[0])
  684.  
  685. def __copy__(self):
  686. return self.copy()
  687.  
  688. def __deepcopy__(self, memo):
  689. return self.deepcopy(memo=memo)
  690.  
  691. def __repr__(self):
  692. return "%s(%r)" % (self.__class__.__name__, list(iteritems(self, multi=True)))
  693.  
  694.  
  695. class _omd_bucket(object):
  696. """Wraps values in the :class:`OrderedMultiDict`. This makes it
  697. possible to keep an order over multiple different keys. It requires
  698. a lot of extra memory and slows down access a lot, but makes it
  699. possible to access elements in O(1) and iterate in O(n).
  700. """
  701.  
  702. __slots__ = ("prev", "key", "value", "next")
  703.  
  704. def __init__(self, omd, key, value):
  705. self.prev = omd._last_bucket
  706. self.key = key
  707. self.value = value
  708. self.next = None
  709.  
  710. if omd._first_bucket is None:
  711. omd._first_bucket = self
  712. if omd._last_bucket is not None:
  713. omd._last_bucket.next = self
  714. omd._last_bucket = self
  715.  
  716. def unlink(self, omd):
  717. if self.prev:
  718. self.prev.next = self.next
  719. if self.next:
  720. self.next.prev = self.prev
  721. if omd._first_bucket is self:
  722. omd._first_bucket = self.next
  723. if omd._last_bucket is self:
  724. omd._last_bucket = self.prev
  725.  
  726.  
  727. @native_itermethods(["keys", "values", "items", "lists", "listvalues"])
  728. class OrderedMultiDict(MultiDict):
  729. """Works like a regular :class:`MultiDict` but preserves the
  730. order of the fields. To convert the ordered multi dict into a
  731. list you can use the :meth:`items` method and pass it ``multi=True``.
  732.  
  733. In general an :class:`OrderedMultiDict` is an order of magnitude
  734. slower than a :class:`MultiDict`.
  735.  
  736. .. admonition:: note
  737.  
  738. Due to a limitation in Python you cannot convert an ordered
  739. multi dict into a regular dict by using ``dict(multidict)``.
  740. Instead you have to use the :meth:`to_dict` method, otherwise
  741. the internal bucket objects are exposed.
  742. """
  743.  
  744. def __init__(self, mapping=None):
  745. dict.__init__(self)
  746. self._first_bucket = self._last_bucket = None
  747. if mapping is not None:
  748. OrderedMultiDict.update(self, mapping)
  749.  
  750. def __eq__(self, other):
  751. if not isinstance(other, MultiDict):
  752. return NotImplemented
  753. if isinstance(other, OrderedMultiDict):
  754. iter1 = iteritems(self, multi=True)
  755. iter2 = iteritems(other, multi=True)
  756. try:
  757. for k1, v1 in iter1:
  758. k2, v2 = next(iter2)
  759. if k1 != k2 or v1 != v2:
  760. return False
  761. except StopIteration:
  762. return False
  763. try:
  764. next(iter2)
  765. except StopIteration:
  766. return True
  767. return False
  768. if len(self) != len(other):
  769. return False
  770. for key, values in iterlists(self):
  771. if other.getlist(key) != values:
  772. return False
  773. return True
  774.  
  775. __hash__ = None
  776.  
  777. def __ne__(self, other):
  778. return not self.__eq__(other)
  779.  
  780. def __reduce_ex__(self, protocol):
  781. return type(self), (list(iteritems(self, multi=True)),)
  782.  
  783. def __getstate__(self):
  784. return list(iteritems(self, multi=True))
  785.  
  786. def __setstate__(self, values):
  787. dict.clear(self)
  788. for key, value in values:
  789. self.add(key, value)
  790.  
  791. def __getitem__(self, key):
  792. if key in self:
  793. return dict.__getitem__(self, key)[0].value
  794. raise exceptions.BadRequestKeyError(key)
  795.  
  796. def __setitem__(self, key, value):
  797. self.poplist(key)
  798. self.add(key, value)
  799.  
  800. def __delitem__(self, key):
  801. self.pop(key)
  802.  
  803. def keys(self):
  804. return (key for key, value in iteritems(self))
  805.  
  806. __iter__ = keys
  807.  
  808. def values(self):
  809. return (value for key, value in iteritems(self))
  810.  
  811. def items(self, multi=False):
  812. ptr = self._first_bucket
  813. if multi:
  814. while ptr is not None:
  815. yield ptr.key, ptr.value
  816. ptr = ptr.next
  817. else:
  818. returned_keys = set()
  819. while ptr is not None:
  820. if ptr.key not in returned_keys:
  821. returned_keys.add(ptr.key)
  822. yield ptr.key, ptr.value
  823. ptr = ptr.next
  824.  
  825. def lists(self):
  826. returned_keys = set()
  827. ptr = self._first_bucket
  828. while ptr is not None:
  829. if ptr.key not in returned_keys:
  830. yield ptr.key, self.getlist(ptr.key)
  831. returned_keys.add(ptr.key)
  832. ptr = ptr.next
  833.  
  834. def listvalues(self):
  835. for _key, values in iterlists(self):
  836. yield values
  837.  
  838. def add(self, key, value):
  839. dict.setdefault(self, key, []).append(_omd_bucket(self, key, value))
  840.  
  841. def getlist(self, key, type=None):
  842. try:
  843. rv = dict.__getitem__(self, key)
  844. except KeyError:
  845. return []
  846. if type is None:
  847. return [x.value for x in rv]
  848. result = []
  849. for item in rv:
  850. try:
  851. result.append(type(item.value))
  852. except ValueError:
  853. pass
  854. return result
  855.  
  856. def setlist(self, key, new_list):
  857. self.poplist(key)
  858. for value in new_list:
  859. self.add(key, value)
  860.  
  861. def setlistdefault(self, key, default_list=None):
  862. raise TypeError("setlistdefault is unsupported for ordered multi dicts")
  863.  
  864. def update(self, mapping):
  865. for key, value in iter_multi_items(mapping):
  866. OrderedMultiDict.add(self, key, value)
  867.  
  868. def poplist(self, key):
  869. buckets = dict.pop(self, key, ())
  870. for bucket in buckets:
  871. bucket.unlink(self)
  872. return [x.value for x in buckets]
  873.  
  874. def pop(self, key, default=_missing):
  875. try:
  876. buckets = dict.pop(self, key)
  877. except KeyError:
  878. if default is not _missing:
  879. return default
  880. raise exceptions.BadRequestKeyError(key)
  881. for bucket in buckets:
  882. bucket.unlink(self)
  883. return buckets[0].value
  884.  
  885. def popitem(self):
  886. try:
  887. key, buckets = dict.popitem(self)
  888. except KeyError as e:
  889. raise exceptions.BadRequestKeyError(e.args[0])
  890. for bucket in buckets:
  891. bucket.unlink(self)
  892. return key, buckets[0].value
  893.  
  894. def popitemlist(self):
  895. try:
  896. key, buckets = dict.popitem(self)
  897. except KeyError as e:
  898. raise exceptions.BadRequestKeyError(e.args[0])
  899. for bucket in buckets:
  900. bucket.unlink(self)
  901. return key, [x.value for x in buckets]
  902.  
  903.  
  904. def _options_header_vkw(value, kw):
  905. return dump_options_header(
  906. value, dict((k.replace("_", "-"), v) for k, v in kw.items())
  907. )
  908.  
  909.  
  910. def _unicodify_header_value(value):
  911. if isinstance(value, bytes):
  912. value = value.decode("latin-1")
  913. if not isinstance(value, text_type):
  914. value = text_type(value)
  915. return value
  916.  
  917.  
  918. @native_itermethods(["keys", "values", "items"])
  919. class Headers(object):
  920. """An object that stores some headers. It has a dict-like interface
  921. but is ordered and can store the same keys multiple times.
  922.  
  923. This data structure is useful if you want a nicer way to handle WSGI
  924. headers which are stored as tuples in a list.
  925.  
  926. From Werkzeug 0.3 onwards, the :exc:`KeyError` raised by this class is
  927. also a subclass of the :class:`~exceptions.BadRequest` HTTP exception
  928. and will render a page for a ``400 BAD REQUEST`` if caught in a
  929. catch-all for HTTP exceptions.
  930.  
  931. Headers is mostly compatible with the Python :class:`wsgiref.headers.Headers`
  932. class, with the exception of `__getitem__`. :mod:`wsgiref` will return
  933. `None` for ``headers['missing']``, whereas :class:`Headers` will raise
  934. a :class:`KeyError`.
  935.  
  936. To create a new :class:`Headers` object pass it a list or dict of headers
  937. which are used as default values. This does not reuse the list passed
  938. to the constructor for internal usage.
  939.  
  940. :param defaults: The list of default values for the :class:`Headers`.
  941.  
  942. .. versionchanged:: 0.9
  943. This data structure now stores unicode values similar to how the
  944. multi dicts do it. The main difference is that bytes can be set as
  945. well which will automatically be latin1 decoded.
  946.  
  947. .. versionchanged:: 0.9
  948. The :meth:`linked` function was removed without replacement as it
  949. was an API that does not support the changes to the encoding model.
  950. """
  951.  
  952. def __init__(self, defaults=None):
  953. self._list = []
  954. if defaults is not None:
  955. if isinstance(defaults, (list, Headers)):
  956. self._list.extend(defaults)
  957. else:
  958. self.extend(defaults)
  959.  
  960. def __getitem__(self, key, _get_mode=False):
  961. if not _get_mode:
  962. if isinstance(key, integer_types):
  963. return self._list[key]
  964. elif isinstance(key, slice):
  965. return self.__class__(self._list[key])
  966. if not isinstance(key, string_types):
  967. raise exceptions.BadRequestKeyError(key)
  968. ikey = key.lower()
  969. for k, v in self._list:
  970. if k.lower() == ikey:
  971. return v
  972. # micro optimization: if we are in get mode we will catch that
  973. # exception one stack level down so we can raise a standard
  974. # key error instead of our special one.
  975. if _get_mode:
  976. raise KeyError()
  977. raise exceptions.BadRequestKeyError(key)
  978.  
  979. def __eq__(self, other):
  980. return other.__class__ is self.__class__ and set(other._list) == set(self._list)
  981.  
  982. __hash__ = None
  983.  
  984. def __ne__(self, other):
  985. return not self.__eq__(other)
  986.  
  987. def get(self, key, default=None, type=None, as_bytes=False):
  988. """Return the default value if the requested data doesn't exist.
  989. If `type` is provided and is a callable it should convert the value,
  990. return it or raise a :exc:`ValueError` if that is not possible. In
  991. this case the function will return the default as if the value was not
  992. found:
  993.  
  994. >>> d = Headers([('Content-Length', '42')])
  995. >>> d.get('Content-Length', type=int)
  996. 42
  997.  
  998. If a headers object is bound you must not add unicode strings
  999. because no encoding takes place.
  1000.  
  1001. .. versionadded:: 0.9
  1002. Added support for `as_bytes`.
  1003.  
  1004. :param key: The key to be looked up.
  1005. :param default: The default value to be returned if the key can't
  1006. be looked up. If not further specified `None` is
  1007. returned.
  1008. :param type: A callable that is used to cast the value in the
  1009. :class:`Headers`. If a :exc:`ValueError` is raised
  1010. by this callable the default value is returned.
  1011. :param as_bytes: return bytes instead of unicode strings.
  1012. """
  1013. try:
  1014. rv = self.__getitem__(key, _get_mode=True)
  1015. except KeyError:
  1016. return default
  1017. if as_bytes:
  1018. rv = rv.encode("latin1")
  1019. if type is None:
  1020. return rv
  1021. try:
  1022. return type(rv)
  1023. except ValueError:
  1024. return default
  1025.  
  1026. def getlist(self, key, type=None, as_bytes=False):
  1027. """Return the list of items for a given key. If that key is not in the
  1028. :class:`Headers`, the return value will be an empty list. Just as
  1029. :meth:`get` :meth:`getlist` accepts a `type` parameter. All items will
  1030. be converted with the callable defined there.
  1031.  
  1032. .. versionadded:: 0.9
  1033. Added support for `as_bytes`.
  1034.  
  1035. :param key: The key to be looked up.
  1036. :param type: A callable that is used to cast the value in the
  1037. :class:`Headers`. If a :exc:`ValueError` is raised
  1038. by this callable the value will be removed from the list.
  1039. :return: a :class:`list` of all the values for the key.
  1040. :param as_bytes: return bytes instead of unicode strings.
  1041. """
  1042. ikey = key.lower()
  1043. result = []
  1044. for k, v in self:
  1045. if k.lower() == ikey:
  1046. if as_bytes:
  1047. v = v.encode("latin1")
  1048. if type is not None:
  1049. try:
  1050. v = type(v)
  1051. except ValueError:
  1052. continue
  1053. result.append(v)
  1054. return result
  1055.  
  1056. def get_all(self, name):
  1057. """Return a list of all the values for the named field.
  1058.  
  1059. This method is compatible with the :mod:`wsgiref`
  1060. :meth:`~wsgiref.headers.Headers.get_all` method.
  1061. """
  1062. return self.getlist(name)
  1063.  
  1064. def items(self, lower=False):
  1065. for key, value in self:
  1066. if lower:
  1067. key = key.lower()
  1068. yield key, value
  1069.  
  1070. def keys(self, lower=False):
  1071. for key, _ in iteritems(self, lower):
  1072. yield key
  1073.  
  1074. def values(self):
  1075. for _, value in iteritems(self):
  1076. yield value
  1077.  
  1078. def extend(self, iterable):
  1079. """Extend the headers with a dict or an iterable yielding keys and
  1080. values.
  1081. """
  1082. if isinstance(iterable, dict):
  1083. for key, value in iteritems(iterable):
  1084. if isinstance(value, (tuple, list)):
  1085. for v in value:
  1086. self.add(key, v)
  1087. else:
  1088. self.add(key, value)
  1089. else:
  1090. for key, value in iterable:
  1091. self.add(key, value)
  1092.  
  1093. def __delitem__(self, key, _index_operation=True):
  1094. if _index_operation and isinstance(key, (integer_types, slice)):
  1095. del self._list[key]
  1096. return
  1097. key = key.lower()
  1098. new = []
  1099. for k, v in self._list:
  1100. if k.lower() != key:
  1101. new.append((k, v))
  1102. self._list[:] = new
  1103.  
  1104. def remove(self, key):
  1105. """Remove a key.
  1106.  
  1107. :param key: The key to be removed.
  1108. """
  1109. return self.__delitem__(key, _index_operation=False)
  1110.  
  1111. def pop(self, key=None, default=_missing):
  1112. """Removes and returns a key or index.
  1113.  
  1114. :param key: The key to be popped. If this is an integer the item at
  1115. that position is removed, if it's a string the value for
  1116. that key is. If the key is omitted or `None` the last
  1117. item is removed.
  1118. :return: an item.
  1119. """
  1120. if key is None:
  1121. return self._list.pop()
  1122. if isinstance(key, integer_types):
  1123. return self._list.pop(key)
  1124. try:
  1125. rv = self[key]
  1126. self.remove(key)
  1127. except KeyError:
  1128. if default is not _missing:
  1129. return default
  1130. raise
  1131. return rv
  1132.  
  1133. def popitem(self):
  1134. """Removes a key or index and returns a (key, value) item."""
  1135. return self.pop()
  1136.  
  1137. def __contains__(self, key):
  1138. """Check if a key is present."""
  1139. try:
  1140. self.__getitem__(key, _get_mode=True)
  1141. except KeyError:
  1142. return False
  1143. return True
  1144.  
  1145. has_key = __contains__
  1146.  
  1147. def __iter__(self):
  1148. """Yield ``(key, value)`` tuples."""
  1149. return iter(self._list)
  1150.  
  1151. def __len__(self):
  1152. return len(self._list)
  1153.  
  1154. def add(self, _key, _value, **kw):
  1155. """Add a new header tuple to the list.
  1156.  
  1157. Keyword arguments can specify additional parameters for the header
  1158. value, with underscores converted to dashes::
  1159.  
  1160. >>> d = Headers()
  1161. >>> d.add('Content-Type', 'text/plain')
  1162. >>> d.add('Content-Disposition', 'attachment', filename='foo.png')
  1163.  
  1164. The keyword argument dumping uses :func:`dump_options_header`
  1165. behind the scenes.
  1166.  
  1167. .. versionadded:: 0.4.1
  1168. keyword arguments were added for :mod:`wsgiref` compatibility.
  1169. """
  1170. if kw:
  1171. _value = _options_header_vkw(_value, kw)
  1172. _key = _unicodify_header_value(_key)
  1173. _value = _unicodify_header_value(_value)
  1174. self._validate_value(_value)
  1175. self._list.append((_key, _value))
  1176.  
  1177. def _validate_value(self, value):
  1178. if not isinstance(value, text_type):
  1179. raise TypeError("Value should be unicode.")
  1180. if u"\n" in value or u"\r" in value:
  1181. raise ValueError(
  1182. "Detected newline in header value. This is "
  1183. "a potential security problem"
  1184. )
  1185.  
  1186. def add_header(self, _key, _value, **_kw):
  1187. """Add a new header tuple to the list.
  1188.  
  1189. An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
  1190. :meth:`~wsgiref.headers.Headers.add_header` method.
  1191. """
  1192. self.add(_key, _value, **_kw)
  1193.  
  1194. def clear(self):
  1195. """Clears all headers."""
  1196. del self._list[:]
  1197.  
  1198. def set(self, _key, _value, **kw):
  1199. """Remove all header tuples for `key` and add a new one. The newly
  1200. added key either appears at the end of the list if there was no
  1201. entry or replaces the first one.
  1202.  
  1203. Keyword arguments can specify additional parameters for the header
  1204. value, with underscores converted to dashes. See :meth:`add` for
  1205. more information.
  1206.  
  1207. .. versionchanged:: 0.6.1
  1208. :meth:`set` now accepts the same arguments as :meth:`add`.
  1209.  
  1210. :param key: The key to be inserted.
  1211. :param value: The value to be inserted.
  1212. """
  1213. if kw:
  1214. _value = _options_header_vkw(_value, kw)
  1215. _key = _unicodify_header_value(_key)
  1216. _value = _unicodify_header_value(_value)
  1217. self._validate_value(_value)
  1218. if not self._list:
  1219. self._list.append((_key, _value))
  1220. return
  1221. listiter = iter(self._list)
  1222. ikey = _key.lower()
  1223. for idx, (old_key, _old_value) in enumerate(listiter):
  1224. if old_key.lower() == ikey:
  1225. # replace first ocurrence
  1226. self._list[idx] = (_key, _value)
  1227. break
  1228. else:
  1229. self._list.append((_key, _value))
  1230. return
  1231. self._list[idx + 1 :] = [t for t in listiter if t[0].lower() != ikey]
  1232.  
  1233. def setdefault(self, key, default):
  1234. """Returns the value for the key if it is in the dict, otherwise it
  1235. returns `default` and sets that value for `key`.
  1236.  
  1237. :param key: The key to be looked up.
  1238. :param default: The default value to be returned if the key is not
  1239. in the dict. If not further specified it's `None`.
  1240. """
  1241. if key in self:
  1242. return self[key]
  1243. self.set(key, default)
  1244. return default
  1245.  
  1246. def __setitem__(self, key, value):
  1247. """Like :meth:`set` but also supports index/slice based setting."""
  1248. if isinstance(key, (slice, integer_types)):
  1249. if isinstance(key, integer_types):
  1250. value = [value]
  1251. value = [
  1252. (_unicodify_header_value(k), _unicodify_header_value(v))
  1253. for (k, v) in value
  1254. ]
  1255. [self._validate_value(v) for (k, v) in value]
  1256. if isinstance(key, integer_types):
  1257. self._list[key] = value[0]
  1258. else:
  1259. self._list[key] = value
  1260. else:
  1261. self.set(key, value)
  1262.  
  1263. def to_list(self, charset="iso-8859-1"):
  1264. """Convert the headers into a list suitable for WSGI.
  1265.  
  1266. .. deprecated:: 0.9
  1267. """
  1268. from warnings import warn
  1269.  
  1270. warn(
  1271. "'to_list' deprecated as of version 0.9 and will be removed"
  1272. " in version 1.0. Use 'to_wsgi_list' instead.",
  1273. DeprecationWarning,
  1274. stacklevel=2,
  1275. )
  1276. return self.to_wsgi_list()
  1277.  
  1278. def to_wsgi_list(self):
  1279. """Convert the headers into a list suitable for WSGI.
  1280.  
  1281. The values are byte strings in Python 2 converted to latin1 and unicode
  1282. strings in Python 3 for the WSGI server to encode.
  1283.  
  1284. :return: list
  1285. """
  1286. if PY2:
  1287. return [(to_native(k), v.encode("latin1")) for k, v in self]
  1288. return list(self)
  1289.  
  1290. def copy(self):
  1291. return self.__class__(self._list)
  1292.  
  1293. def __copy__(self):
  1294. return self.copy()
  1295.  
  1296. def __str__(self):
  1297. """Returns formatted headers suitable for HTTP transmission."""
  1298. strs = []
  1299. for key, value in self.to_wsgi_list():
  1300. strs.append("%s: %s" % (key, value))
  1301. strs.append("\r\n")
  1302. return "\r\n".join(strs)
  1303.  
  1304. def __repr__(self):
  1305. return "%s(%r)" % (self.__class__.__name__, list(self))
  1306.  
  1307.  
  1308. class ImmutableHeadersMixin(object):
  1309. """Makes a :class:`Headers` immutable. We do not mark them as
  1310. hashable though since the only usecase for this datastructure
  1311. in Werkzeug is a view on a mutable structure.
  1312.  
  1313. .. versionadded:: 0.5
  1314.  
  1315. :private:
  1316. """
  1317.  
  1318. def __delitem__(self, key, **kwargs):
  1319. is_immutable(self)
  1320.  
  1321. def __setitem__(self, key, value):
  1322. is_immutable(self)
  1323.  
  1324. set = __setitem__
  1325.  
  1326. def add(self, item):
  1327. is_immutable(self)
  1328.  
  1329. remove = add_header = add
  1330.  
  1331. def extend(self, iterable):
  1332. is_immutable(self)
  1333.  
  1334. def insert(self, pos, value):
  1335. is_immutable(self)
  1336.  
  1337. def pop(self, index=-1):
  1338. is_immutable(self)
  1339.  
  1340. def popitem(self):
  1341. is_immutable(self)
  1342.  
  1343. def setdefault(self, key, default):
  1344. is_immutable(self)
  1345.  
  1346.  
  1347. class EnvironHeaders(ImmutableHeadersMixin, Headers):
  1348. """Read only version of the headers from a WSGI environment. This
  1349. provides the same interface as `Headers` and is constructed from
  1350. a WSGI environment.
  1351.  
  1352. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
  1353. subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
  1354. render a page for a ``400 BAD REQUEST`` if caught in a catch-all for
  1355. HTTP exceptions.
  1356. """
  1357.  
  1358. def __init__(self, environ):
  1359. self.environ = environ
  1360.  
  1361. def __eq__(self, other):
  1362. return self.environ is other.environ
  1363.  
  1364. __hash__ = None
  1365.  
  1366. def __getitem__(self, key, _get_mode=False):
  1367. # _get_mode is a no-op for this class as there is no index but
  1368. # used because get() calls it.
  1369. if not isinstance(key, string_types):
  1370. raise KeyError(key)
  1371. key = key.upper().replace("-", "_")
  1372. if key in ("CONTENT_TYPE", "CONTENT_LENGTH"):
  1373. return _unicodify_header_value(self.environ[key])
  1374. return _unicodify_header_value(self.environ["HTTP_" + key])
  1375.  
  1376. def __len__(self):
  1377. # the iter is necessary because otherwise list calls our
  1378. # len which would call list again and so forth.
  1379. return len(list(iter(self)))
  1380.  
  1381. def __iter__(self):
  1382. for key, value in iteritems(self.environ):
  1383. if key.startswith("HTTP_") and key not in (
  1384. "HTTP_CONTENT_TYPE",
  1385. "HTTP_CONTENT_LENGTH",
  1386. ):
  1387. yield (
  1388. key[5:].replace("_", "-").title(),
  1389. _unicodify_header_value(value),
  1390. )
  1391. elif key in ("CONTENT_TYPE", "CONTENT_LENGTH") and value:
  1392. yield (key.replace("_", "-").title(), _unicodify_header_value(value))
  1393.  
  1394. def copy(self):
  1395. raise TypeError("cannot create %r copies" % self.__class__.__name__)
  1396.  
  1397.  
  1398. @native_itermethods(["keys", "values", "items", "lists", "listvalues"])
  1399. class CombinedMultiDict(ImmutableMultiDictMixin, MultiDict):
  1400. """A read only :class:`MultiDict` that you can pass multiple :class:`MultiDict`
  1401. instances as sequence and it will combine the return values of all wrapped
  1402. dicts:
  1403.  
  1404. >>> from werkzeug.datastructures import CombinedMultiDict, MultiDict
  1405. >>> post = MultiDict([('foo', 'bar')])
  1406. >>> get = MultiDict([('blub', 'blah')])
  1407. >>> combined = CombinedMultiDict([get, post])
  1408. >>> combined['foo']
  1409. 'bar'
  1410. >>> combined['blub']
  1411. 'blah'
  1412.  
  1413. This works for all read operations and will raise a `TypeError` for
  1414. methods that usually change data which isn't possible.
  1415.  
  1416. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
  1417. subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
  1418. render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP
  1419. exceptions.
  1420. """
  1421.  
  1422. def __reduce_ex__(self, protocol):
  1423. return type(self), (self.dicts,)
  1424.  
  1425. def __init__(self, dicts=None):
  1426. self.dicts = dicts or []
  1427.  
  1428. @classmethod
  1429. def fromkeys(cls):
  1430. raise TypeError("cannot create %r instances by fromkeys" % cls.__name__)
  1431.  
  1432. def __getitem__(self, key):
  1433. for d in self.dicts:
  1434. if key in d:
  1435. return d[key]
  1436. raise exceptions.BadRequestKeyError(key)
  1437.  
  1438. def get(self, key, default=None, type=None):
  1439. for d in self.dicts:
  1440. if key in d:
  1441. if type is not None:
  1442. try:
  1443. return type(d[key])
  1444. except ValueError:
  1445. continue
  1446. return d[key]
  1447. return default
  1448.  
  1449. def getlist(self, key, type=None):
  1450. rv = []
  1451. for d in self.dicts:
  1452. rv.extend(d.getlist(key, type))
  1453. return rv
  1454.  
  1455. def _keys_impl(self):
  1456. """This function exists so __len__ can be implemented more efficiently,
  1457. saving one list creation from an iterator.
  1458.  
  1459. Using this for Python 2's ``dict.keys`` behavior would be useless since
  1460. `dict.keys` in Python 2 returns a list, while we have a set here.
  1461. """
  1462. rv = set()
  1463. for d in self.dicts:
  1464. rv.update(iterkeys(d))
  1465. return rv
  1466.  
  1467. def keys(self):
  1468. return iter(self._keys_impl())
  1469.  
  1470. __iter__ = keys
  1471.  
  1472. def items(self, multi=False):
  1473. found = set()
  1474. for d in self.dicts:
  1475. for key, value in iteritems(d, multi):
  1476. if multi:
  1477. yield key, value
  1478. elif key not in found:
  1479. found.add(key)
  1480. yield key, value
  1481.  
  1482. def values(self):
  1483. for _key, value in iteritems(self):
  1484. yield value
  1485.  
  1486. def lists(self):
  1487. rv = {}
  1488. for d in self.dicts:
  1489. for key, values in iterlists(d):
  1490. rv.setdefault(key, []).extend(values)
  1491. return iteritems(rv)
  1492.  
  1493. def listvalues(self):
  1494. return (x[1] for x in self.lists())
  1495.  
  1496. def copy(self):
  1497. """Return a shallow mutable copy of this object.
  1498.  
  1499. This returns a :class:`MultiDict` representing the data at the
  1500. time of copying. The copy will no longer reflect changes to the
  1501. wrapped dicts.
  1502.  
  1503. .. versionchanged:: 0.15
  1504. Return a mutable :class:`MultiDict`.
  1505. """
  1506. return MultiDict(self)
  1507.  
  1508. def to_dict(self, flat=True):
  1509. """Return the contents as regular dict. If `flat` is `True` the
  1510. returned dict will only have the first item present, if `flat` is
  1511. `False` all values will be returned as lists.
  1512.  
  1513. :param flat: If set to `False` the dict returned will have lists
  1514. with all the values in it. Otherwise it will only
  1515. contain the first item for each key.
  1516. :return: a :class:`dict`
  1517. """
  1518. rv = {}
  1519. for d in reversed(self.dicts):
  1520. rv.update(d.to_dict(flat))
  1521. return rv
  1522.  
  1523. def __len__(self):
  1524. return len(self._keys_impl())
  1525.  
  1526. def __contains__(self, key):
  1527. for d in self.dicts:
  1528. if key in d:
  1529. return True
  1530. return False
  1531.  
  1532. has_key = __contains__
  1533.  
  1534. def __repr__(self):
  1535. return "%s(%r)" % (self.__class__.__name__, self.dicts)
  1536.  
  1537.  
  1538. class FileMultiDict(MultiDict):
  1539. """A special :class:`MultiDict` that has convenience methods to add
  1540. files to it. This is used for :class:`EnvironBuilder` and generally
  1541. useful for unittesting.
  1542.  
  1543. .. versionadded:: 0.5
  1544. """
  1545.  
  1546. def add_file(self, name, file, filename=None, content_type=None):
  1547. """Adds a new file to the dict. `file` can be a file name or
  1548. a :class:`file`-like or a :class:`FileStorage` object.
  1549.  
  1550. :param name: the name of the field.
  1551. :param file: a filename or :class:`file`-like object
  1552. :param filename: an optional filename
  1553. :param content_type: an optional content type
  1554. """
  1555. if isinstance(file, FileStorage):
  1556. value = file
  1557. else:
  1558. if isinstance(file, string_types):
  1559. if filename is None:
  1560. filename = file
  1561. file = open(file, "rb")
  1562. if filename and content_type is None:
  1563. content_type = (
  1564. mimetypes.guess_type(filename)[0] or "application/octet-stream"
  1565. )
  1566. value = FileStorage(file, filename, name, content_type)
  1567.  
  1568. self.add(name, value)
  1569.  
  1570.  
  1571. class ImmutableDict(ImmutableDictMixin, dict):
  1572. """An immutable :class:`dict`.
  1573.  
  1574. .. versionadded:: 0.5
  1575. """
  1576.  
  1577. def __repr__(self):
  1578. return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
  1579.  
  1580. def copy(self):
  1581. """Return a shallow mutable copy of this object. Keep in mind that
  1582. the standard library's :func:`copy` function is a no-op for this class
  1583. like for any other python immutable type (eg: :class:`tuple`).
  1584. """
  1585. return dict(self)
  1586.  
  1587. def __copy__(self):
  1588. return self
  1589.  
  1590.  
  1591. class ImmutableMultiDict(ImmutableMultiDictMixin, MultiDict):
  1592. """An immutable :class:`MultiDict`.
  1593.  
  1594. .. versionadded:: 0.5
  1595. """
  1596.  
  1597. def copy(self):
  1598. """Return a shallow mutable copy of this object. Keep in mind that
  1599. the standard library's :func:`copy` function is a no-op for this class
  1600. like for any other python immutable type (eg: :class:`tuple`).
  1601. """
  1602. return MultiDict(self)
  1603.  
  1604. def __copy__(self):
  1605. return self
  1606.  
  1607.  
  1608. class ImmutableOrderedMultiDict(ImmutableMultiDictMixin, OrderedMultiDict):
  1609. """An immutable :class:`OrderedMultiDict`.
  1610.  
  1611. .. versionadded:: 0.6
  1612. """
  1613.  
  1614. def _iter_hashitems(self):
  1615. return enumerate(iteritems(self, multi=True))
  1616.  
  1617. def copy(self):
  1618. """Return a shallow mutable copy of this object. Keep in mind that
  1619. the standard library's :func:`copy` function is a no-op for this class
  1620. like for any other python immutable type (eg: :class:`tuple`).
  1621. """
  1622. return OrderedMultiDict(self)
  1623.  
  1624. def __copy__(self):
  1625. return self
  1626.  
  1627.  
  1628. @native_itermethods(["values"])
  1629. class Accept(ImmutableList):
  1630. """An :class:`Accept` object is just a list subclass for lists of
  1631. ``(value, quality)`` tuples. It is automatically sorted by specificity
  1632. and quality.
  1633.  
  1634. All :class:`Accept` objects work similar to a list but provide extra
  1635. functionality for working with the data. Containment checks are
  1636. normalized to the rules of that header:
  1637.  
  1638. >>> a = CharsetAccept([('ISO-8859-1', 1), ('utf-8', 0.7)])
  1639. >>> a.best
  1640. 'ISO-8859-1'
  1641. >>> 'iso-8859-1' in a
  1642. True
  1643. >>> 'UTF8' in a
  1644. True
  1645. >>> 'utf7' in a
  1646. False
  1647.  
  1648. To get the quality for an item you can use normal item lookup:
  1649.  
  1650. >>> print a['utf-8']
  1651. 0.7
  1652. >>> a['utf7']
  1653. 0
  1654.  
  1655. .. versionchanged:: 0.5
  1656. :class:`Accept` objects are forced immutable now.
  1657. """
  1658.  
  1659. def __init__(self, values=()):
  1660. if values is None:
  1661. list.__init__(self)
  1662. self.provided = False
  1663. elif isinstance(values, Accept):
  1664. self.provided = values.provided
  1665. list.__init__(self, values)
  1666. else:
  1667. self.provided = True
  1668. values = sorted(
  1669. values,
  1670. key=lambda x: (self._specificity(x[0]), x[1], x[0]),
  1671. reverse=True,
  1672. )
  1673. list.__init__(self, values)
  1674.  
  1675. def _specificity(self, value):
  1676. """Returns a tuple describing the value's specificity."""
  1677. return (value != "*",)
  1678.  
  1679. def _value_matches(self, value, item):
  1680. """Check if a value matches a given accept item."""
  1681. return item == "*" or item.lower() == value.lower()
  1682.  
  1683. def __getitem__(self, key):
  1684. """Besides index lookup (getting item n) you can also pass it a string
  1685. to get the quality for the item. If the item is not in the list, the
  1686. returned quality is ``0``.
  1687. """
  1688. if isinstance(key, string_types):
  1689. return self.quality(key)
  1690. return list.__getitem__(self, key)
  1691.  
  1692. def quality(self, key):
  1693. """Returns the quality of the key.
  1694.  
  1695. .. versionadded:: 0.6
  1696. In previous versions you had to use the item-lookup syntax
  1697. (eg: ``obj[key]`` instead of ``obj.quality(key)``)
  1698. """
  1699. for item, quality in self:
  1700. if self._value_matches(key, item):
  1701. return quality
  1702. return 0
  1703.  
  1704. def __contains__(self, value):
  1705. for item, _quality in self:
  1706. if self._value_matches(value, item):
  1707. return True
  1708. return False
  1709.  
  1710. def __repr__(self):
  1711. return "%s([%s])" % (
  1712. self.__class__.__name__,
  1713. ", ".join("(%r, %s)" % (x, y) for x, y in self),
  1714. )
  1715.  
  1716. def index(self, key):
  1717. """Get the position of an entry or raise :exc:`ValueError`.
  1718.  
  1719. :param key: The key to be looked up.
  1720.  
  1721. .. versionchanged:: 0.5
  1722. This used to raise :exc:`IndexError`, which was inconsistent
  1723. with the list API.
  1724. """
  1725. if isinstance(key, string_types):
  1726. for idx, (item, _quality) in enumerate(self):
  1727. if self._value_matches(key, item):
  1728. return idx
  1729. raise ValueError(key)
  1730. return list.index(self, key)
  1731.  
  1732. def find(self, key):
  1733. """Get the position of an entry or return -1.
  1734.  
  1735. :param key: The key to be looked up.
  1736. """
  1737. try:
  1738. return self.index(key)
  1739. except ValueError:
  1740. return -1
  1741.  
  1742. def values(self):
  1743. """Iterate over all values."""
  1744. for item in self:
  1745. yield item[0]
  1746.  
  1747. def to_header(self):
  1748. """Convert the header set into an HTTP header string."""
  1749. result = []
  1750. for value, quality in self:
  1751. if quality != 1:
  1752. value = "%s;q=%s" % (value, quality)
  1753. result.append(value)
  1754. return ",".join(result)
  1755.  
  1756. def __str__(self):
  1757. return self.to_header()
  1758.  
  1759. def _best_single_match(self, match):
  1760. for client_item, quality in self:
  1761. if self._value_matches(match, client_item):
  1762. # self is sorted by specificity descending, we can exit
  1763. return client_item, quality
  1764.  
  1765. def best_match(self, matches, default=None):
  1766. """Returns the best match from a list of possible matches based
  1767. on the specificity and quality of the client. If two items have the
  1768. same quality and specificity, the one is returned that comes first.
  1769.  
  1770. :param matches: a list of matches to check for
  1771. :param default: the value that is returned if none match
  1772. """
  1773. result = default
  1774. best_quality = -1
  1775. best_specificity = (-1,)
  1776. for server_item in matches:
  1777. match = self._best_single_match(server_item)
  1778. if not match:
  1779. continue
  1780. client_item, quality = match
  1781. specificity = self._specificity(client_item)
  1782. if quality <= 0 or quality < best_quality:
  1783. continue
  1784. # better quality or same quality but more specific => better match
  1785. if quality > best_quality or specificity > best_specificity:
  1786. result = server_item
  1787. best_quality = quality
  1788. best_specificity = specificity
  1789. return result
  1790.  
  1791. @property
  1792. def best(self):
  1793. """The best match as value."""
  1794. if self:
  1795. return self[0][0]
  1796.  
  1797.  
  1798. class MIMEAccept(Accept):
  1799. """Like :class:`Accept` but with special methods and behavior for
  1800. mimetypes.
  1801. """
  1802.  
  1803. def _specificity(self, value):
  1804. return tuple(x != "*" for x in value.split("/", 1))
  1805.  
  1806. def _value_matches(self, value, item):
  1807. def _normalize(x):
  1808. x = x.lower()
  1809. return ("*", "*") if x == "*" else x.split("/", 1)
  1810.  
  1811. # this is from the application which is trusted. to avoid developer
  1812. # frustration we actually check these for valid values
  1813. if "/" not in value:
  1814. raise ValueError("invalid mimetype %r" % value)
  1815. value_type, value_subtype = _normalize(value)
  1816. if value_type == "*" and value_subtype != "*":
  1817. raise ValueError("invalid mimetype %r" % value)
  1818.  
  1819. if "/" not in item:
  1820. return False
  1821. item_type, item_subtype = _normalize(item)
  1822. if item_type == "*" and item_subtype != "*":
  1823. return False
  1824. return (
  1825. item_type == item_subtype == "*" or value_type == value_subtype == "*"
  1826. ) or (
  1827. item_type == value_type
  1828. and (
  1829. item_subtype == "*"
  1830. or value_subtype == "*"
  1831. or item_subtype == value_subtype
  1832. )
  1833. )
  1834.  
  1835. @property
  1836. def accept_html(self):
  1837. """True if this object accepts HTML."""
  1838. return (
  1839. "text/html" in self or "application/xhtml+xml" in self or self.accept_xhtml
  1840. )
  1841.  
  1842. @property
  1843. def accept_xhtml(self):
  1844. """True if this object accepts XHTML."""
  1845. return "application/xhtml+xml" in self or "application/xml" in self
  1846.  
  1847. @property
  1848. def accept_json(self):
  1849. """True if this object accepts JSON."""
  1850. return "application/json" in self
  1851.  
  1852.  
  1853. class LanguageAccept(Accept):
  1854. """Like :class:`Accept` but with normalization for languages."""
  1855.  
  1856. def _value_matches(self, value, item):
  1857. def _normalize(language):
  1858. return _locale_delim_re.split(language.lower())
  1859.  
  1860. return item == "*" or _normalize(value) == _normalize(item)
  1861.  
  1862.  
  1863. class CharsetAccept(Accept):
  1864. """Like :class:`Accept` but with normalization for charsets."""
  1865.  
  1866. def _value_matches(self, value, item):
  1867. def _normalize(name):
  1868. try:
  1869. return codecs.lookup(name).name
  1870. except LookupError:
  1871. return name.lower()
  1872.  
  1873. return item == "*" or _normalize(value) == _normalize(item)
  1874.  
  1875.  
  1876. def cache_property(key, empty, type):
  1877. """Return a new property object for a cache header. Useful if you
  1878. want to add support for a cache extension in a subclass."""
  1879. return property(
  1880. lambda x: x._get_cache_value(key, empty, type),
  1881. lambda x, v: x._set_cache_value(key, v, type),
  1882. lambda x: x._del_cache_value(key),
  1883. "accessor for %r" % key,
  1884. )
  1885.  
  1886.  
  1887. class _CacheControl(UpdateDictMixin, dict):
  1888. """Subclass of a dict that stores values for a Cache-Control header. It
  1889. has accessors for all the cache-control directives specified in RFC 2616.
  1890. The class does not differentiate between request and response directives.
  1891.  
  1892. Because the cache-control directives in the HTTP header use dashes the
  1893. python descriptors use underscores for that.
  1894.  
  1895. To get a header of the :class:`CacheControl` object again you can convert
  1896. the object into a string or call the :meth:`to_header` method. If you plan
  1897. to subclass it and add your own items have a look at the sourcecode for
  1898. that class.
  1899.  
  1900. .. versionchanged:: 0.4
  1901.  
  1902. Setting `no_cache` or `private` to boolean `True` will set the implicit
  1903. none-value which is ``*``:
  1904.  
  1905. >>> cc = ResponseCacheControl()
  1906. >>> cc.no_cache = True
  1907. >>> cc
  1908. <ResponseCacheControl 'no-cache'>
  1909. >>> cc.no_cache
  1910. '*'
  1911. >>> cc.no_cache = None
  1912. >>> cc
  1913. <ResponseCacheControl ''>
  1914.  
  1915. In versions before 0.5 the behavior documented here affected the now
  1916. no longer existing `CacheControl` class.
  1917. """
  1918.  
  1919. no_cache = cache_property("no-cache", "*", None)
  1920. no_store = cache_property("no-store", None, bool)
  1921. max_age = cache_property("max-age", -1, int)
  1922. no_transform = cache_property("no-transform", None, None)
  1923.  
  1924. def __init__(self, values=(), on_update=None):
  1925. dict.__init__(self, values or ())
  1926. self.on_update = on_update
  1927. self.provided = values is not None
  1928.  
  1929. def _get_cache_value(self, key, empty, type):
  1930. """Used internally by the accessor properties."""
  1931. if type is bool:
  1932. return key in self
  1933. if key in self:
  1934. value = self[key]
  1935. if value is None:
  1936. return empty
  1937. elif type is not None:
  1938. try:
  1939. value = type(value)
  1940. except ValueError:
  1941. pass
  1942. return value
  1943.  
  1944. def _set_cache_value(self, key, value, type):
  1945. """Used internally by the accessor properties."""
  1946. if type is bool:
  1947. if value:
  1948. self[key] = None
  1949. else:
  1950. self.pop(key, None)
  1951. else:
  1952. if value is None:
  1953. self.pop(key)
  1954. elif value is True:
  1955. self[key] = None
  1956. else:
  1957. self[key] = value
  1958.  
  1959. def _del_cache_value(self, key):
  1960. """Used internally by the accessor properties."""
  1961. if key in self:
  1962. del self[key]
  1963.  
  1964. def to_header(self):
  1965. """Convert the stored values into a cache control header."""
  1966. return dump_header(self)
  1967.  
  1968. def __str__(self):
  1969. return self.to_header()
  1970.  
  1971. def __repr__(self):
  1972. return "<%s %s>" % (
  1973. self.__class__.__name__,
  1974. " ".join("%s=%r" % (k, v) for k, v in sorted(self.items())),
  1975. )
  1976.  
  1977.  
  1978. class RequestCacheControl(ImmutableDictMixin, _CacheControl):
  1979. """A cache control for requests. This is immutable and gives access
  1980. to all the request-relevant cache control headers.
  1981.  
  1982. To get a header of the :class:`RequestCacheControl` object again you can
  1983. convert the object into a string or call the :meth:`to_header` method. If
  1984. you plan to subclass it and add your own items have a look at the sourcecode
  1985. for that class.
  1986.  
  1987. .. versionadded:: 0.5
  1988. In previous versions a `CacheControl` class existed that was used
  1989. both for request and response.
  1990. """
  1991.  
  1992. max_stale = cache_property("max-stale", "*", int)
  1993. min_fresh = cache_property("min-fresh", "*", int)
  1994. no_transform = cache_property("no-transform", None, None)
  1995. only_if_cached = cache_property("only-if-cached", None, bool)
  1996.  
  1997.  
  1998. class ResponseCacheControl(_CacheControl):
  1999. """A cache control for responses. Unlike :class:`RequestCacheControl`
  2000. this is mutable and gives access to response-relevant cache control
  2001. headers.
  2002.  
  2003. To get a header of the :class:`ResponseCacheControl` object again you can
  2004. convert the object into a string or call the :meth:`to_header` method. If
  2005. you plan to subclass it and add your own items have a look at the sourcecode
  2006. for that class.
  2007.  
  2008. .. versionadded:: 0.5
  2009. In previous versions a `CacheControl` class existed that was used
  2010. both for request and response.
  2011. """
  2012.  
  2013. public = cache_property("public", None, bool)
  2014. private = cache_property("private", "*", None)
  2015. must_revalidate = cache_property("must-revalidate", None, bool)
  2016. proxy_revalidate = cache_property("proxy-revalidate", None, bool)
  2017. s_maxage = cache_property("s-maxage", None, None)
  2018.  
  2019.  
  2020. # attach cache_property to the _CacheControl as staticmethod
  2021. # so that others can reuse it.
  2022. _CacheControl.cache_property = staticmethod(cache_property)
  2023.  
  2024.  
  2025. class CallbackDict(UpdateDictMixin, dict):
  2026. """A dict that calls a function passed every time something is changed.
  2027. The function is passed the dict instance.
  2028. """
  2029.  
  2030. def __init__(self, initial=None, on_update=None):
  2031. dict.__init__(self, initial or ())
  2032. self.on_update = on_update
  2033.  
  2034. def __repr__(self):
  2035. return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))
  2036.  
  2037.  
  2038. class HeaderSet(collections_abc.MutableSet):
  2039. """Similar to the :class:`ETags` class this implements a set-like structure.
  2040. Unlike :class:`ETags` this is case insensitive and used for vary, allow, and
  2041. content-language headers.
  2042.  
  2043. If not constructed using the :func:`parse_set_header` function the
  2044. instantiation works like this:
  2045.  
  2046. >>> hs = HeaderSet(['foo', 'bar', 'baz'])
  2047. >>> hs
  2048. HeaderSet(['foo', 'bar', 'baz'])
  2049. """
  2050.  
  2051. def __init__(self, headers=None, on_update=None):
  2052. self._headers = list(headers or ())
  2053. self._set = set([x.lower() for x in self._headers])
  2054. self.on_update = on_update
  2055.  
  2056. def add(self, header):
  2057. """Add a new header to the set."""
  2058. self.update((header,))
  2059.  
  2060. def remove(self, header):
  2061. """Remove a header from the set. This raises an :exc:`KeyError` if the
  2062. header is not in the set.
  2063.  
  2064. .. versionchanged:: 0.5
  2065. In older versions a :exc:`IndexError` was raised instead of a
  2066. :exc:`KeyError` if the object was missing.
  2067.  
  2068. :param header: the header to be removed.
  2069. """
  2070. key = header.lower()
  2071. if key not in self._set:
  2072. raise KeyError(header)
  2073. self._set.remove(key)
  2074. for idx, key in enumerate(self._headers):
  2075. if key.lower() == header:
  2076. del self._headers[idx]
  2077. break
  2078. if self.on_update is not None:
  2079. self.on_update(self)
  2080.  
  2081. def update(self, iterable):
  2082. """Add all the headers from the iterable to the set.
  2083.  
  2084. :param iterable: updates the set with the items from the iterable.
  2085. """
  2086. inserted_any = False
  2087. for header in iterable:
  2088. key = header.lower()
  2089. if key not in self._set:
  2090. self._headers.append(header)
  2091. self._set.add(key)
  2092. inserted_any = True
  2093. if inserted_any and self.on_update is not None:
  2094. self.on_update(self)
  2095.  
  2096. def discard(self, header):
  2097. """Like :meth:`remove` but ignores errors.
  2098.  
  2099. :param header: the header to be discarded.
  2100. """
  2101. try:
  2102. return self.remove(header)
  2103. except KeyError:
  2104. pass
  2105.  
  2106. def find(self, header):
  2107. """Return the index of the header in the set or return -1 if not found.
  2108.  
  2109. :param header: the header to be looked up.
  2110. """
  2111. header = header.lower()
  2112. for idx, item in enumerate(self._headers):
  2113. if item.lower() == header:
  2114. return idx
  2115. return -1
  2116.  
  2117. def index(self, header):
  2118. """Return the index of the header in the set or raise an
  2119. :exc:`IndexError`.
  2120.  
  2121. :param header: the header to be looked up.
  2122. """
  2123. rv = self.find(header)
  2124. if rv < 0:
  2125. raise IndexError(header)
  2126. return rv
  2127.  
  2128. def clear(self):
  2129. """Clear the set."""
  2130. self._set.clear()
  2131. del self._headers[:]
  2132. if self.on_update is not None:
  2133. self.on_update(self)
  2134.  
  2135. def as_set(self, preserve_casing=False):
  2136. """Return the set as real python set type. When calling this, all
  2137. the items are converted to lowercase and the ordering is lost.
  2138.  
  2139. :param preserve_casing: if set to `True` the items in the set returned
  2140. will have the original case like in the
  2141. :class:`HeaderSet`, otherwise they will
  2142. be lowercase.
  2143. """
  2144. if preserve_casing:
  2145. return set(self._headers)
  2146. return set(self._set)
  2147.  
  2148. def to_header(self):
  2149. """Convert the header set into an HTTP header string."""
  2150. return ", ".join(map(quote_header_value, self._headers))
  2151.  
  2152. def __getitem__(self, idx):
  2153. return self._headers[idx]
  2154.  
  2155. def __delitem__(self, idx):
  2156. rv = self._headers.pop(idx)
  2157. self._set.remove(rv.lower())
  2158. if self.on_update is not None:
  2159. self.on_update(self)
  2160.  
  2161. def __setitem__(self, idx, value):
  2162. old = self._headers[idx]
  2163. self._set.remove(old.lower())
  2164. self._headers[idx] = value
  2165. self._set.add(value.lower())
  2166. if self.on_update is not None:
  2167. self.on_update(self)
  2168.  
  2169. def __contains__(self, header):
  2170. return header.lower() in self._set
  2171.  
  2172. def __len__(self):
  2173. return len(self._set)
  2174.  
  2175. def __iter__(self):
  2176. return iter(self._headers)
  2177.  
  2178. def __nonzero__(self):
  2179. return bool(self._set)
  2180.  
  2181. def __str__(self):
  2182. return self.to_header()
  2183.  
  2184. def __repr__(self):
  2185. return "%s(%r)" % (self.__class__.__name__, self._headers)
  2186.  
  2187.  
  2188. class ETags(collections_abc.Container, collections_abc.Iterable):
  2189. """A set that can be used to check if one etag is present in a collection
  2190. of etags.
  2191. """
  2192.  
  2193. def __init__(self, strong_etags=None, weak_etags=None, star_tag=False):
  2194. self._strong = frozenset(not star_tag and strong_etags or ())
  2195. self._weak = frozenset(weak_etags or ())
  2196. self.star_tag = star_tag
  2197.  
  2198. def as_set(self, include_weak=False):
  2199. """Convert the `ETags` object into a python set. Per default all the
  2200. weak etags are not part of this set."""
  2201. rv = set(self._strong)
  2202. if include_weak:
  2203. rv.update(self._weak)
  2204. return rv
  2205.  
  2206. def is_weak(self, etag):
  2207. """Check if an etag is weak."""
  2208. return etag in self._weak
  2209.  
  2210. def is_strong(self, etag):
  2211. """Check if an etag is strong."""
  2212. return etag in self._strong
  2213.  
  2214. def contains_weak(self, etag):
  2215. """Check if an etag is part of the set including weak and strong tags."""
  2216. return self.is_weak(etag) or self.contains(etag)
  2217.  
  2218. def contains(self, etag):
  2219. """Check if an etag is part of the set ignoring weak tags.
  2220. It is also possible to use the ``in`` operator.
  2221. """
  2222. if self.star_tag:
  2223. return True
  2224. return self.is_strong(etag)
  2225.  
  2226. def contains_raw(self, etag):
  2227. """When passed a quoted tag it will check if this tag is part of the
  2228. set. If the tag is weak it is checked against weak and strong tags,
  2229. otherwise strong only."""
  2230. etag, weak = unquote_etag(etag)
  2231. if weak:
  2232. return self.contains_weak(etag)
  2233. return self.contains(etag)
  2234.  
  2235. def to_header(self):
  2236. """Convert the etags set into a HTTP header string."""
  2237. if self.star_tag:
  2238. return "*"
  2239. return ", ".join(
  2240. ['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak]
  2241. )
  2242.  
  2243. def __call__(self, etag=None, data=None, include_weak=False):
  2244. if [etag, data].count(None) != 1:
  2245. raise TypeError("either tag or data required, but at least one")
  2246. if etag is None:
  2247. etag = generate_etag(data)
  2248. if include_weak:
  2249. if etag in self._weak:
  2250. return True
  2251. return etag in self._strong
  2252.  
  2253. def __bool__(self):
  2254. return bool(self.star_tag or self._strong or self._weak)
  2255.  
  2256. __nonzero__ = __bool__
  2257.  
  2258. def __str__(self):
  2259. return self.to_header()
  2260.  
  2261. def __iter__(self):
  2262. return iter(self._strong)
  2263.  
  2264. def __contains__(self, etag):
  2265. return self.contains(etag)
  2266.  
  2267. def __repr__(self):
  2268. return "<%s %r>" % (self.__class__.__name__, str(self))
  2269.  
  2270.  
  2271. class IfRange(object):
  2272. """Very simple object that represents the `If-Range` header in parsed
  2273. form. It will either have neither a etag or date or one of either but
  2274. never both.
  2275.  
  2276. .. versionadded:: 0.7
  2277. """
  2278.  
  2279. def __init__(self, etag=None, date=None):
  2280. #: The etag parsed and unquoted. Ranges always operate on strong
  2281. #: etags so the weakness information is not necessary.
  2282. self.etag = etag
  2283. #: The date in parsed format or `None`.
  2284. self.date = date
  2285.  
  2286. def to_header(self):
  2287. """Converts the object back into an HTTP header."""
  2288. if self.date is not None:
  2289. return http_date(self.date)
  2290. if self.etag is not None:
  2291. return quote_etag(self.etag)
  2292. return ""
  2293.  
  2294. def __str__(self):
  2295. return self.to_header()
  2296.  
  2297. def __repr__(self):
  2298. return "<%s %r>" % (self.__class__.__name__, str(self))
  2299.  
  2300.  
  2301. class Range(object):
  2302. """Represents a ``Range`` header. All methods only support only
  2303. bytes as the unit. Stores a list of ranges if given, but the methods
  2304. only work if only one range is provided.
  2305.  
  2306. :raise ValueError: If the ranges provided are invalid.
  2307.  
  2308. .. versionchanged:: 0.15
  2309. The ranges passed in are validated.
  2310.  
  2311. .. versionadded:: 0.7
  2312. """
  2313.  
  2314. def __init__(self, units, ranges):
  2315. #: The units of this range. Usually "bytes".
  2316. self.units = units
  2317. #: A list of ``(begin, end)`` tuples for the range header provided.
  2318. #: The ranges are non-inclusive.
  2319. self.ranges = ranges
  2320.  
  2321. for start, end in ranges:
  2322. if start is None or (end is not None and (start < 0 or start >= end)):
  2323. raise ValueError("{} is not a valid range.".format((start, end)))
  2324.  
  2325. def range_for_length(self, length):
  2326. """If the range is for bytes, the length is not None and there is
  2327. exactly one range and it is satisfiable it returns a ``(start, stop)``
  2328. tuple, otherwise `None`.
  2329. """
  2330. if self.units != "bytes" or length is None or len(self.ranges) != 1:
  2331. return None
  2332. start, end = self.ranges[0]
  2333. if end is None:
  2334. end = length
  2335. if start < 0:
  2336. start += length
  2337. if is_byte_range_valid(start, end, length):
  2338. return start, min(end, length)
  2339.  
  2340. def make_content_range(self, length):
  2341. """Creates a :class:`~werkzeug.datastructures.ContentRange` object
  2342. from the current range and given content length.
  2343. """
  2344. rng = self.range_for_length(length)
  2345. if rng is not None:
  2346. return ContentRange(self.units, rng[0], rng[1], length)
  2347.  
  2348. def to_header(self):
  2349. """Converts the object back into an HTTP header."""
  2350. ranges = []
  2351. for begin, end in self.ranges:
  2352. if end is None:
  2353. ranges.append("%s-" % begin if begin >= 0 else str(begin))
  2354. else:
  2355. ranges.append("%s-%s" % (begin, end - 1))
  2356. return "%s=%s" % (self.units, ",".join(ranges))
  2357.  
  2358. def to_content_range_header(self, length):
  2359. """Converts the object into `Content-Range` HTTP header,
  2360. based on given length
  2361. """
  2362. range_for_length = self.range_for_length(length)
  2363. if range_for_length is not None:
  2364. return "%s %d-%d/%d" % (
  2365. self.units,
  2366. range_for_length[0],
  2367. range_for_length[1] - 1,
  2368. length,
  2369. )
  2370. return None
  2371.  
  2372. def __str__(self):
  2373. return self.to_header()
  2374.  
  2375. def __repr__(self):
  2376. return "<%s %r>" % (self.__class__.__name__, str(self))
  2377.  
  2378.  
  2379. class ContentRange(object):
  2380. """Represents the content range header.
  2381.  
  2382. .. versionadded:: 0.7
  2383. """
  2384.  
  2385. def __init__(self, units, start, stop, length=None, on_update=None):
  2386. assert is_byte_range_valid(start, stop, length), "Bad range provided"
  2387. self.on_update = on_update
  2388. self.set(start, stop, length, units)
  2389.  
  2390. def _callback_property(name): # noqa: B902
  2391. def fget(self):
  2392. return getattr(self, name)
  2393.  
  2394. def fset(self, value):
  2395. setattr(self, name, value)
  2396. if self.on_update is not None:
  2397. self.on_update(self)
  2398.  
  2399. return property(fget, fset)
  2400.  
  2401. #: The units to use, usually "bytes"
  2402. units = _callback_property("_units")
  2403. #: The start point of the range or `None`.
  2404. start = _callback_property("_start")
  2405. #: The stop point of the range (non-inclusive) or `None`. Can only be
  2406. #: `None` if also start is `None`.
  2407. stop = _callback_property("_stop")
  2408. #: The length of the range or `None`.
  2409. length = _callback_property("_length")
  2410. del _callback_property
  2411.  
  2412. def set(self, start, stop, length=None, units="bytes"):
  2413. """Simple method to update the ranges."""
  2414. assert is_byte_range_valid(start, stop, length), "Bad range provided"
  2415. self._units = units
  2416. self._start = start
  2417. self._stop = stop
  2418. self._length = length
  2419. if self.on_update is not None:
  2420. self.on_update(self)
  2421.  
  2422. def unset(self):
  2423. """Sets the units to `None` which indicates that the header should
  2424. no longer be used.
  2425. """
  2426. self.set(None, None, units=None)
  2427.  
  2428. def to_header(self):
  2429. if self.units is None:
  2430. return ""
  2431. if self.length is None:
  2432. length = "*"
  2433. else:
  2434. length = self.length
  2435. if self.start is None:
  2436. return "%s */%s" % (self.units, length)
  2437. return "%s %s-%s/%s" % (self.units, self.start, self.stop - 1, length)
  2438.  
  2439. def __nonzero__(self):
  2440. return self.units is not None
  2441.  
  2442. __bool__ = __nonzero__
  2443.  
  2444. def __str__(self):
  2445. return self.to_header()
  2446.  
  2447. def __repr__(self):
  2448. return "<%s %r>" % (self.__class__.__name__, str(self))
  2449.  
  2450.  
  2451. class Authorization(ImmutableDictMixin, dict):
  2452. """Represents an `Authorization` header sent by the client. You should
  2453. not create this kind of object yourself but use it when it's returned by
  2454. the `parse_authorization_header` function.
  2455.  
  2456. This object is a dict subclass and can be altered by setting dict items
  2457. but it should be considered immutable as it's returned by the client and
  2458. not meant for modifications.
  2459.  
  2460. .. versionchanged:: 0.5
  2461. This object became immutable.
  2462. """
  2463.  
  2464. def __init__(self, auth_type, data=None):
  2465. dict.__init__(self, data or {})
  2466. self.type = auth_type
  2467.  
  2468. username = property(
  2469. lambda self: self.get("username"),
  2470. doc="""
  2471. The username transmitted. This is set for both basic and digest
  2472. auth all the time.""",
  2473. )
  2474. password = property(
  2475. lambda self: self.get("password"),
  2476. doc="""
  2477. When the authentication type is basic this is the password
  2478. transmitted by the client, else `None`.""",
  2479. )
  2480. realm = property(
  2481. lambda self: self.get("realm"),
  2482. doc="""
  2483. This is the server realm sent back for HTTP digest auth.""",
  2484. )
  2485. nonce = property(
  2486. lambda self: self.get("nonce"),
  2487. doc="""
  2488. The nonce the server sent for digest auth, sent back by the client.
  2489. A nonce should be unique for every 401 response for HTTP digest
  2490. auth.""",
  2491. )
  2492. uri = property(
  2493. lambda self: self.get("uri"),
  2494. doc="""
  2495. The URI from Request-URI of the Request-Line; duplicated because
  2496. proxies are allowed to change the Request-Line in transit. HTTP
  2497. digest auth only.""",
  2498. )
  2499. nc = property(
  2500. lambda self: self.get("nc"),
  2501. doc="""
  2502. The nonce count value transmitted by clients if a qop-header is
  2503. also transmitted. HTTP digest auth only.""",
  2504. )
  2505. cnonce = property(
  2506. lambda self: self.get("cnonce"),
  2507. doc="""
  2508. If the server sent a qop-header in the ``WWW-Authenticate``
  2509. header, the client has to provide this value for HTTP digest auth.
  2510. See the RFC for more details.""",
  2511. )
  2512. response = property(
  2513. lambda self: self.get("response"),
  2514. doc="""
  2515. A string of 32 hex digits computed as defined in RFC 2617, which
  2516. proves that the user knows a password. Digest auth only.""",
  2517. )
  2518. opaque = property(
  2519. lambda self: self.get("opaque"),
  2520. doc="""
  2521. The opaque header from the server returned unchanged by the client.
  2522. It is recommended that this string be base64 or hexadecimal data.
  2523. Digest auth only.""",
  2524. )
  2525. qop = property(
  2526. lambda self: self.get("qop"),
  2527. doc="""
  2528. Indicates what "quality of protection" the client has applied to
  2529. the message for HTTP digest auth. Note that this is a single token,
  2530. not a quoted list of alternatives as in WWW-Authenticate.""",
  2531. )
  2532.  
  2533.  
  2534. class WWWAuthenticate(UpdateDictMixin, dict):
  2535. """Provides simple access to `WWW-Authenticate` headers."""
  2536.  
  2537. #: list of keys that require quoting in the generated header
  2538. _require_quoting = frozenset(["domain", "nonce", "opaque", "realm", "qop"])
  2539.  
  2540. def __init__(self, auth_type=None, values=None, on_update=None):
  2541. dict.__init__(self, values or ())
  2542. if auth_type:
  2543. self["__auth_type__"] = auth_type
  2544. self.on_update = on_update
  2545.  
  2546. def set_basic(self, realm="authentication required"):
  2547. """Clear the auth info and enable basic auth."""
  2548. dict.clear(self)
  2549. dict.update(self, {"__auth_type__": "basic", "realm": realm})
  2550. if self.on_update:
  2551. self.on_update(self)
  2552.  
  2553. def set_digest(
  2554. self, realm, nonce, qop=("auth",), opaque=None, algorithm=None, stale=False
  2555. ):
  2556. """Clear the auth info and enable digest auth."""
  2557. d = {
  2558. "__auth_type__": "digest",
  2559. "realm": realm,
  2560. "nonce": nonce,
  2561. "qop": dump_header(qop),
  2562. }
  2563. if stale:
  2564. d["stale"] = "TRUE"
  2565. if opaque is not None:
  2566. d["opaque"] = opaque
  2567. if algorithm is not None:
  2568. d["algorithm"] = algorithm
  2569. dict.clear(self)
  2570. dict.update(self, d)
  2571. if self.on_update:
  2572. self.on_update(self)
  2573.  
  2574. def to_header(self):
  2575. """Convert the stored values into a WWW-Authenticate header."""
  2576. d = dict(self)
  2577. auth_type = d.pop("__auth_type__", None) or "basic"
  2578. return "%s %s" % (
  2579. auth_type.title(),
  2580. ", ".join(
  2581. [
  2582. "%s=%s"
  2583. % (
  2584. key,
  2585. quote_header_value(
  2586. value, allow_token=key not in self._require_quoting
  2587. ),
  2588. )
  2589. for key, value in iteritems(d)
  2590. ]
  2591. ),
  2592. )
  2593.  
  2594. def __str__(self):
  2595. return self.to_header()
  2596.  
  2597. def __repr__(self):
  2598. return "<%s %r>" % (self.__class__.__name__, self.to_header())
  2599.  
  2600. def auth_property(name, doc=None): # noqa: B902
  2601. """A static helper function for subclasses to add extra authentication
  2602. system properties onto a class::
  2603.  
  2604. class FooAuthenticate(WWWAuthenticate):
  2605. special_realm = auth_property('special_realm')
  2606.  
  2607. For more information have a look at the sourcecode to see how the
  2608. regular properties (:attr:`realm` etc.) are implemented.
  2609. """
  2610.  
  2611. def _set_value(self, value):
  2612. if value is None:
  2613. self.pop(name, None)
  2614. else:
  2615. self[name] = str(value)
  2616.  
  2617. return property(lambda x: x.get(name), _set_value, doc=doc)
  2618.  
  2619. def _set_property(name, doc=None): # noqa: B902
  2620. def fget(self):
  2621. def on_update(header_set):
  2622. if not header_set and name in self:
  2623. del self[name]
  2624. elif header_set:
  2625. self[name] = header_set.to_header()
  2626.  
  2627. return parse_set_header(self.get(name), on_update)
  2628.  
  2629. return property(fget, doc=doc)
  2630.  
  2631. type = auth_property(
  2632. "__auth_type__",
  2633. doc="""The type of the auth mechanism. HTTP currently specifies
  2634. ``Basic`` and ``Digest``.""",
  2635. )
  2636. realm = auth_property(
  2637. "realm",
  2638. doc="""A string to be displayed to users so they know which
  2639. username and password to use. This string should contain at
  2640. least the name of the host performing the authentication and
  2641. might additionally indicate the collection of users who might
  2642. have access.""",
  2643. )
  2644. domain = _set_property(
  2645. "domain",
  2646. doc="""A list of URIs that define the protection space. If a URI
  2647. is an absolute path, it is relative to the canonical root URL of
  2648. the server being accessed.""",
  2649. )
  2650. nonce = auth_property(
  2651. "nonce",
  2652. doc="""
  2653. A server-specified data string which should be uniquely generated
  2654. each time a 401 response is made. It is recommended that this
  2655. string be base64 or hexadecimal data.""",
  2656. )
  2657. opaque = auth_property(
  2658. "opaque",
  2659. doc="""A string of data, specified by the server, which should
  2660. be returned by the client unchanged in the Authorization header
  2661. of subsequent requests with URIs in the same protection space.
  2662. It is recommended that this string be base64 or hexadecimal
  2663. data.""",
  2664. )
  2665. algorithm = auth_property(
  2666. "algorithm",
  2667. doc="""A string indicating a pair of algorithms used to produce
  2668. the digest and a checksum. If this is not present it is assumed
  2669. to be "MD5". If the algorithm is not understood, the challenge
  2670. should be ignored (and a different one used, if there is more
  2671. than one).""",
  2672. )
  2673. qop = _set_property(
  2674. "qop",
  2675. doc="""A set of quality-of-privacy directives such as auth and
  2676. auth-int.""",
  2677. )
  2678.  
  2679. @property
  2680. def stale(self):
  2681. """A flag, indicating that the previous request from the client
  2682. was rejected because the nonce value was stale.
  2683. """
  2684. val = self.get("stale")
  2685. if val is not None:
  2686. return val.lower() == "true"
  2687.  
  2688. @stale.setter
  2689. def stale(self, value):
  2690. if value is None:
  2691. self.pop("stale", None)
  2692. else:
  2693. self["stale"] = "TRUE" if value else "FALSE"
  2694.  
  2695. auth_property = staticmethod(auth_property)
  2696. del _set_property
  2697.  
  2698.  
  2699. class FileStorage(object):
  2700. """The :class:`FileStorage` class is a thin wrapper over incoming files.
  2701. It is used by the request object to represent uploaded files. All the
  2702. attributes of the wrapper stream are proxied by the file storage so
  2703. it's possible to do ``storage.read()`` instead of the long form
  2704. ``storage.stream.read()``.
  2705. """
  2706.  
  2707. def __init__(
  2708. self,
  2709. stream=None,
  2710. filename=None,
  2711. name=None,
  2712. content_type=None,
  2713. content_length=None,
  2714. headers=None,
  2715. ):
  2716. self.name = name
  2717. self.stream = stream or BytesIO()
  2718.  
  2719. # if no filename is provided we can attempt to get the filename
  2720. # from the stream object passed. There we have to be careful to
  2721. # skip things like <fdopen>, <stderr> etc. Python marks these
  2722. # special filenames with angular brackets.
  2723. if filename is None:
  2724. filename = getattr(stream, "name", None)
  2725. s = make_literal_wrapper(filename)
  2726. if filename and filename[0] == s("<") and filename[-1] == s(">"):
  2727. filename = None
  2728.  
  2729. # On Python 3 we want to make sure the filename is always unicode.
  2730. # This might not be if the name attribute is bytes due to the
  2731. # file being opened from the bytes API.
  2732. if not PY2 and isinstance(filename, bytes):
  2733. filename = filename.decode(get_filesystem_encoding(), "replace")
  2734.  
  2735. self.filename = filename
  2736. if headers is None:
  2737. headers = Headers()
  2738. self.headers = headers
  2739. if content_type is not None:
  2740. headers["Content-Type"] = content_type
  2741. if content_length is not None:
  2742. headers["Content-Length"] = str(content_length)
  2743.  
  2744. def _parse_content_type(self):
  2745. if not hasattr(self, "_parsed_content_type"):
  2746. self._parsed_content_type = parse_options_header(self.content_type)
  2747.  
  2748. @property
  2749. def content_type(self):
  2750. """The content-type sent in the header. Usually not available"""
  2751. return self.headers.get("content-type")
  2752.  
  2753. @property
  2754. def content_length(self):
  2755. """The content-length sent in the header. Usually not available"""
  2756. return int(self.headers.get("content-length") or 0)
  2757.  
  2758. @property
  2759. def mimetype(self):
  2760. """Like :attr:`content_type`, but without parameters (eg, without
  2761. charset, type etc.) and always lowercase. For example if the content
  2762. type is ``text/HTML; charset=utf-8`` the mimetype would be
  2763. ``'text/html'``.
  2764.  
  2765. .. versionadded:: 0.7
  2766. """
  2767. self._parse_content_type()
  2768. return self._parsed_content_type[0].lower()
  2769.  
  2770. @property
  2771. def mimetype_params(self):
  2772. """The mimetype parameters as dict. For example if the content
  2773. type is ``text/html; charset=utf-8`` the params would be
  2774. ``{'charset': 'utf-8'}``.
  2775.  
  2776. .. versionadded:: 0.7
  2777. """
  2778. self._parse_content_type()
  2779. return self._parsed_content_type[1]
  2780.  
  2781. def save(self, dst, buffer_size=16384):
  2782. """Save the file to a destination path or file object. If the
  2783. destination is a file object you have to close it yourself after the
  2784. call. The buffer size is the number of bytes held in memory during
  2785. the copy process. It defaults to 16KB.
  2786.  
  2787. For secure file saving also have a look at :func:`secure_filename`.
  2788.  
  2789. :param dst: a filename or open file object the uploaded file
  2790. is saved to.
  2791. :param buffer_size: the size of the buffer. This works the same as
  2792. the `length` parameter of
  2793. :func:`shutil.copyfileobj`.
  2794. """
  2795. from shutil import copyfileobj
  2796.  
  2797. close_dst = False
  2798. if isinstance(dst, string_types):
  2799. dst = open(dst, "wb")
  2800. close_dst = True
  2801. try:
  2802. copyfileobj(self.stream, dst, buffer_size)
  2803. finally:
  2804. if close_dst:
  2805. dst.close()
  2806.  
  2807. def close(self):
  2808. """Close the underlying file if possible."""
  2809. try:
  2810. self.stream.close()
  2811. except Exception:
  2812. pass
  2813.  
  2814. def __nonzero__(self):
  2815. return bool(self.filename)
  2816.  
  2817. __bool__ = __nonzero__
  2818.  
  2819. def __getattr__(self, name):
  2820. try:
  2821. return getattr(self.stream, name)
  2822. except AttributeError:
  2823. # SpooledTemporaryFile doesn't implement IOBase, get the
  2824. # attribute from its backing file instead.
  2825. # https://github.com/python/cpython/pull/3249
  2826. if hasattr(self.stream, "_file"):
  2827. return getattr(self.stream._file, name)
  2828. raise
  2829.  
  2830. def __iter__(self):
  2831. return iter(self.stream)
  2832.  
  2833. def __repr__(self):
  2834. return "<%s: %r (%r)>" % (
  2835. self.__class__.__name__,
  2836. self.filename,
  2837. self.content_type,
  2838. )
  2839.  
  2840.  
  2841. # circular dependencies
  2842. from . import exceptions
  2843. from .http import dump_header
  2844. from .http import dump_options_header
  2845. from .http import generate_etag
  2846. from .http import http_date
  2847. from .http import is_byte_range_valid
  2848. from .http import parse_options_header
  2849. from .http import parse_set_header
  2850. from .http import quote_etag
  2851. from .http import quote_header_value
  2852. from .http import unquote_etag
Add Comment
Please, Sign In to add comment