structures.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. from __future__ import annotations
  2. from collections.abc import MutableSet
  3. from copy import deepcopy
  4. from .. import exceptions
  5. from .._internal import _missing
  6. from .mixins import ImmutableDictMixin
  7. from .mixins import ImmutableListMixin
  8. from .mixins import ImmutableMultiDictMixin
  9. from .mixins import UpdateDictMixin
  10. def is_immutable(self):
  11. raise TypeError(f"{type(self).__name__!r} objects are immutable")
  12. def iter_multi_items(mapping):
  13. """Iterates over the items of a mapping yielding keys and values
  14. without dropping any from more complex structures.
  15. """
  16. if isinstance(mapping, MultiDict):
  17. yield from mapping.items(multi=True)
  18. elif isinstance(mapping, dict):
  19. for key, value in mapping.items():
  20. if isinstance(value, (tuple, list)):
  21. for v in value:
  22. yield key, v
  23. else:
  24. yield key, value
  25. else:
  26. yield from mapping
  27. class ImmutableList(ImmutableListMixin, list):
  28. """An immutable :class:`list`.
  29. .. versionadded:: 0.5
  30. :private:
  31. """
  32. def __repr__(self):
  33. return f"{type(self).__name__}({list.__repr__(self)})"
  34. class TypeConversionDict(dict):
  35. """Works like a regular dict but the :meth:`get` method can perform
  36. type conversions. :class:`MultiDict` and :class:`CombinedMultiDict`
  37. are subclasses of this class and provide the same feature.
  38. .. versionadded:: 0.5
  39. """
  40. def get(self, key, default=None, type=None):
  41. """Return the default value if the requested data doesn't exist.
  42. If `type` is provided and is a callable it should convert the value,
  43. return it or raise a :exc:`ValueError` if that is not possible. In
  44. this case the function will return the default as if the value was not
  45. found:
  46. >>> d = TypeConversionDict(foo='42', bar='blub')
  47. >>> d.get('foo', type=int)
  48. 42
  49. >>> d.get('bar', -1, type=int)
  50. -1
  51. :param key: The key to be looked up.
  52. :param default: The default value to be returned if the key can't
  53. be looked up. If not further specified `None` is
  54. returned.
  55. :param type: A callable that is used to cast the value in the
  56. :class:`MultiDict`. If a :exc:`ValueError` is raised
  57. by this callable the default value is returned.
  58. """
  59. try:
  60. rv = self[key]
  61. except KeyError:
  62. return default
  63. if type is not None:
  64. try:
  65. rv = type(rv)
  66. except ValueError:
  67. rv = default
  68. return rv
  69. class ImmutableTypeConversionDict(ImmutableDictMixin, TypeConversionDict):
  70. """Works like a :class:`TypeConversionDict` but does not support
  71. modifications.
  72. .. versionadded:: 0.5
  73. """
  74. def copy(self):
  75. """Return a shallow mutable copy of this object. Keep in mind that
  76. the standard library's :func:`copy` function is a no-op for this class
  77. like for any other python immutable type (eg: :class:`tuple`).
  78. """
  79. return TypeConversionDict(self)
  80. def __copy__(self):
  81. return self
  82. class MultiDict(TypeConversionDict):
  83. """A :class:`MultiDict` is a dictionary subclass customized to deal with
  84. multiple values for the same key which is for example used by the parsing
  85. functions in the wrappers. This is necessary because some HTML form
  86. elements pass multiple values for the same key.
  87. :class:`MultiDict` implements all standard dictionary methods.
  88. Internally, it saves all values for a key as a list, but the standard dict
  89. access methods will only return the first value for a key. If you want to
  90. gain access to the other values, too, you have to use the `list` methods as
  91. explained below.
  92. Basic Usage:
  93. >>> d = MultiDict([('a', 'b'), ('a', 'c')])
  94. >>> d
  95. MultiDict([('a', 'b'), ('a', 'c')])
  96. >>> d['a']
  97. 'b'
  98. >>> d.getlist('a')
  99. ['b', 'c']
  100. >>> 'a' in d
  101. True
  102. It behaves like a normal dict thus all dict functions will only return the
  103. first value when multiple values for one key are found.
  104. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
  105. subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
  106. render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP
  107. exceptions.
  108. A :class:`MultiDict` can be constructed from an iterable of
  109. ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2
  110. onwards some keyword parameters.
  111. :param mapping: the initial value for the :class:`MultiDict`. Either a
  112. regular dict, an iterable of ``(key, value)`` tuples
  113. or `None`.
  114. """
  115. def __init__(self, mapping=None):
  116. if isinstance(mapping, MultiDict):
  117. dict.__init__(self, ((k, l[:]) for k, l in mapping.lists()))
  118. elif isinstance(mapping, dict):
  119. tmp = {}
  120. for key, value in mapping.items():
  121. if isinstance(value, (tuple, list)):
  122. if len(value) == 0:
  123. continue
  124. value = list(value)
  125. else:
  126. value = [value]
  127. tmp[key] = value
  128. dict.__init__(self, tmp)
  129. else:
  130. tmp = {}
  131. for key, value in mapping or ():
  132. tmp.setdefault(key, []).append(value)
  133. dict.__init__(self, tmp)
  134. def __getstate__(self):
  135. return dict(self.lists())
  136. def __setstate__(self, value):
  137. dict.clear(self)
  138. dict.update(self, value)
  139. def __iter__(self):
  140. # Work around https://bugs.python.org/issue43246.
  141. # (`return super().__iter__()` also works here, which makes this look
  142. # even more like it should be a no-op, yet it isn't.)
  143. return dict.__iter__(self)
  144. def __getitem__(self, key):
  145. """Return the first data value for this key;
  146. raises KeyError if not found.
  147. :param key: The key to be looked up.
  148. :raise KeyError: if the key does not exist.
  149. """
  150. if key in self:
  151. lst = dict.__getitem__(self, key)
  152. if len(lst) > 0:
  153. return lst[0]
  154. raise exceptions.BadRequestKeyError(key)
  155. def __setitem__(self, key, value):
  156. """Like :meth:`add` but removes an existing key first.
  157. :param key: the key for the value.
  158. :param value: the value to set.
  159. """
  160. dict.__setitem__(self, key, [value])
  161. def add(self, key, value):
  162. """Adds a new value for the key.
  163. .. versionadded:: 0.6
  164. :param key: the key for the value.
  165. :param value: the value to add.
  166. """
  167. dict.setdefault(self, key, []).append(value)
  168. def getlist(self, key, type=None):
  169. """Return the list of items for a given key. If that key is not in the
  170. `MultiDict`, the return value will be an empty list. Just like `get`,
  171. `getlist` accepts a `type` parameter. All items will be converted
  172. with the callable defined there.
  173. :param key: The key to be looked up.
  174. :param type: A callable that is used to cast the value in the
  175. :class:`MultiDict`. If a :exc:`ValueError` is raised
  176. by this callable the value will be removed from the list.
  177. :return: a :class:`list` of all the values for the key.
  178. """
  179. try:
  180. rv = dict.__getitem__(self, key)
  181. except KeyError:
  182. return []
  183. if type is None:
  184. return list(rv)
  185. result = []
  186. for item in rv:
  187. try:
  188. result.append(type(item))
  189. except ValueError:
  190. pass
  191. return result
  192. def setlist(self, key, new_list):
  193. """Remove the old values for a key and add new ones. Note that the list
  194. you pass the values in will be shallow-copied before it is inserted in
  195. the dictionary.
  196. >>> d = MultiDict()
  197. >>> d.setlist('foo', ['1', '2'])
  198. >>> d['foo']
  199. '1'
  200. >>> d.getlist('foo')
  201. ['1', '2']
  202. :param key: The key for which the values are set.
  203. :param new_list: An iterable with the new values for the key. Old values
  204. are removed first.
  205. """
  206. dict.__setitem__(self, key, list(new_list))
  207. def setdefault(self, key, default=None):
  208. """Returns the value for the key if it is in the dict, otherwise it
  209. returns `default` and sets that value for `key`.
  210. :param key: The key to be looked up.
  211. :param default: The default value to be returned if the key is not
  212. in the dict. If not further specified it's `None`.
  213. """
  214. if key not in self:
  215. self[key] = default
  216. else:
  217. default = self[key]
  218. return default
  219. def setlistdefault(self, key, default_list=None):
  220. """Like `setdefault` but sets multiple values. The list returned
  221. is not a copy, but the list that is actually used internally. This
  222. means that you can put new values into the dict by appending items
  223. to the list:
  224. >>> d = MultiDict({"foo": 1})
  225. >>> d.setlistdefault("foo").extend([2, 3])
  226. >>> d.getlist("foo")
  227. [1, 2, 3]
  228. :param key: The key to be looked up.
  229. :param default_list: An iterable of default values. It is either copied
  230. (in case it was a list) or converted into a list
  231. before returned.
  232. :return: a :class:`list`
  233. """
  234. if key not in self:
  235. default_list = list(default_list or ())
  236. dict.__setitem__(self, key, default_list)
  237. else:
  238. default_list = dict.__getitem__(self, key)
  239. return default_list
  240. def items(self, multi=False):
  241. """Return an iterator of ``(key, value)`` pairs.
  242. :param multi: If set to `True` the iterator returned will have a pair
  243. for each value of each key. Otherwise it will only
  244. contain pairs for the first value of each key.
  245. """
  246. for key, values in dict.items(self):
  247. if multi:
  248. for value in values:
  249. yield key, value
  250. else:
  251. yield key, values[0]
  252. def lists(self):
  253. """Return a iterator of ``(key, values)`` pairs, where values is the list
  254. of all values associated with the key."""
  255. for key, values in dict.items(self):
  256. yield key, list(values)
  257. def values(self):
  258. """Returns an iterator of the first value on every key's value list."""
  259. for values in dict.values(self):
  260. yield values[0]
  261. def listvalues(self):
  262. """Return an iterator of all values associated with a key. Zipping
  263. :meth:`keys` and this is the same as calling :meth:`lists`:
  264. >>> d = MultiDict({"foo": [1, 2, 3]})
  265. >>> zip(d.keys(), d.listvalues()) == d.lists()
  266. True
  267. """
  268. return dict.values(self)
  269. def copy(self):
  270. """Return a shallow copy of this object."""
  271. return self.__class__(self)
  272. def deepcopy(self, memo=None):
  273. """Return a deep copy of this object."""
  274. return self.__class__(deepcopy(self.to_dict(flat=False), memo))
  275. def to_dict(self, flat=True):
  276. """Return the contents as regular dict. If `flat` is `True` the
  277. returned dict will only have the first item present, if `flat` is
  278. `False` all values will be returned as lists.
  279. :param flat: If set to `False` the dict returned will have lists
  280. with all the values in it. Otherwise it will only
  281. contain the first value for each key.
  282. :return: a :class:`dict`
  283. """
  284. if flat:
  285. return dict(self.items())
  286. return dict(self.lists())
  287. def update(self, mapping):
  288. """update() extends rather than replaces existing key lists:
  289. >>> a = MultiDict({'x': 1})
  290. >>> b = MultiDict({'x': 2, 'y': 3})
  291. >>> a.update(b)
  292. >>> a
  293. MultiDict([('y', 3), ('x', 1), ('x', 2)])
  294. If the value list for a key in ``other_dict`` is empty, no new values
  295. will be added to the dict and the key will not be created:
  296. >>> x = {'empty_list': []}
  297. >>> y = MultiDict()
  298. >>> y.update(x)
  299. >>> y
  300. MultiDict([])
  301. """
  302. for key, value in iter_multi_items(mapping):
  303. MultiDict.add(self, key, value)
  304. def pop(self, key, default=_missing):
  305. """Pop the first item for a list on the dict. Afterwards the
  306. key is removed from the dict, so additional values are discarded:
  307. >>> d = MultiDict({"foo": [1, 2, 3]})
  308. >>> d.pop("foo")
  309. 1
  310. >>> "foo" in d
  311. False
  312. :param key: the key to pop.
  313. :param default: if provided the value to return if the key was
  314. not in the dictionary.
  315. """
  316. try:
  317. lst = dict.pop(self, key)
  318. if len(lst) == 0:
  319. raise exceptions.BadRequestKeyError(key)
  320. return lst[0]
  321. except KeyError:
  322. if default is not _missing:
  323. return default
  324. raise exceptions.BadRequestKeyError(key) from None
  325. def popitem(self):
  326. """Pop an item from the dict."""
  327. try:
  328. item = dict.popitem(self)
  329. if len(item[1]) == 0:
  330. raise exceptions.BadRequestKeyError(item[0])
  331. return (item[0], item[1][0])
  332. except KeyError as e:
  333. raise exceptions.BadRequestKeyError(e.args[0]) from None
  334. def poplist(self, key):
  335. """Pop the list for a key from the dict. If the key is not in the dict
  336. an empty list is returned.
  337. .. versionchanged:: 0.5
  338. If the key does no longer exist a list is returned instead of
  339. raising an error.
  340. """
  341. return dict.pop(self, key, [])
  342. def popitemlist(self):
  343. """Pop a ``(key, list)`` tuple from the dict."""
  344. try:
  345. return dict.popitem(self)
  346. except KeyError as e:
  347. raise exceptions.BadRequestKeyError(e.args[0]) from None
  348. def __copy__(self):
  349. return self.copy()
  350. def __deepcopy__(self, memo):
  351. return self.deepcopy(memo=memo)
  352. def __repr__(self):
  353. return f"{type(self).__name__}({list(self.items(multi=True))!r})"
  354. class _omd_bucket:
  355. """Wraps values in the :class:`OrderedMultiDict`. This makes it
  356. possible to keep an order over multiple different keys. It requires
  357. a lot of extra memory and slows down access a lot, but makes it
  358. possible to access elements in O(1) and iterate in O(n).
  359. """
  360. __slots__ = ("prev", "key", "value", "next")
  361. def __init__(self, omd, key, value):
  362. self.prev = omd._last_bucket
  363. self.key = key
  364. self.value = value
  365. self.next = None
  366. if omd._first_bucket is None:
  367. omd._first_bucket = self
  368. if omd._last_bucket is not None:
  369. omd._last_bucket.next = self
  370. omd._last_bucket = self
  371. def unlink(self, omd):
  372. if self.prev:
  373. self.prev.next = self.next
  374. if self.next:
  375. self.next.prev = self.prev
  376. if omd._first_bucket is self:
  377. omd._first_bucket = self.next
  378. if omd._last_bucket is self:
  379. omd._last_bucket = self.prev
  380. class OrderedMultiDict(MultiDict):
  381. """Works like a regular :class:`MultiDict` but preserves the
  382. order of the fields. To convert the ordered multi dict into a
  383. list you can use the :meth:`items` method and pass it ``multi=True``.
  384. In general an :class:`OrderedMultiDict` is an order of magnitude
  385. slower than a :class:`MultiDict`.
  386. .. admonition:: note
  387. Due to a limitation in Python you cannot convert an ordered
  388. multi dict into a regular dict by using ``dict(multidict)``.
  389. Instead you have to use the :meth:`to_dict` method, otherwise
  390. the internal bucket objects are exposed.
  391. """
  392. def __init__(self, mapping=None):
  393. dict.__init__(self)
  394. self._first_bucket = self._last_bucket = None
  395. if mapping is not None:
  396. OrderedMultiDict.update(self, mapping)
  397. def __eq__(self, other):
  398. if not isinstance(other, MultiDict):
  399. return NotImplemented
  400. if isinstance(other, OrderedMultiDict):
  401. iter1 = iter(self.items(multi=True))
  402. iter2 = iter(other.items(multi=True))
  403. try:
  404. for k1, v1 in iter1:
  405. k2, v2 = next(iter2)
  406. if k1 != k2 or v1 != v2:
  407. return False
  408. except StopIteration:
  409. return False
  410. try:
  411. next(iter2)
  412. except StopIteration:
  413. return True
  414. return False
  415. if len(self) != len(other):
  416. return False
  417. for key, values in self.lists():
  418. if other.getlist(key) != values:
  419. return False
  420. return True
  421. __hash__ = None
  422. def __reduce_ex__(self, protocol):
  423. return type(self), (list(self.items(multi=True)),)
  424. def __getstate__(self):
  425. return list(self.items(multi=True))
  426. def __setstate__(self, values):
  427. dict.clear(self)
  428. for key, value in values:
  429. self.add(key, value)
  430. def __getitem__(self, key):
  431. if key in self:
  432. return dict.__getitem__(self, key)[0].value
  433. raise exceptions.BadRequestKeyError(key)
  434. def __setitem__(self, key, value):
  435. self.poplist(key)
  436. self.add(key, value)
  437. def __delitem__(self, key):
  438. self.pop(key)
  439. def keys(self):
  440. return (key for key, value in self.items())
  441. def __iter__(self):
  442. return iter(self.keys())
  443. def values(self):
  444. return (value for key, value in self.items())
  445. def items(self, multi=False):
  446. ptr = self._first_bucket
  447. if multi:
  448. while ptr is not None:
  449. yield ptr.key, ptr.value
  450. ptr = ptr.next
  451. else:
  452. returned_keys = set()
  453. while ptr is not None:
  454. if ptr.key not in returned_keys:
  455. returned_keys.add(ptr.key)
  456. yield ptr.key, ptr.value
  457. ptr = ptr.next
  458. def lists(self):
  459. returned_keys = set()
  460. ptr = self._first_bucket
  461. while ptr is not None:
  462. if ptr.key not in returned_keys:
  463. yield ptr.key, self.getlist(ptr.key)
  464. returned_keys.add(ptr.key)
  465. ptr = ptr.next
  466. def listvalues(self):
  467. for _key, values in self.lists():
  468. yield values
  469. def add(self, key, value):
  470. dict.setdefault(self, key, []).append(_omd_bucket(self, key, value))
  471. def getlist(self, key, type=None):
  472. try:
  473. rv = dict.__getitem__(self, key)
  474. except KeyError:
  475. return []
  476. if type is None:
  477. return [x.value for x in rv]
  478. result = []
  479. for item in rv:
  480. try:
  481. result.append(type(item.value))
  482. except ValueError:
  483. pass
  484. return result
  485. def setlist(self, key, new_list):
  486. self.poplist(key)
  487. for value in new_list:
  488. self.add(key, value)
  489. def setlistdefault(self, key, default_list=None):
  490. raise TypeError("setlistdefault is unsupported for ordered multi dicts")
  491. def update(self, mapping):
  492. for key, value in iter_multi_items(mapping):
  493. OrderedMultiDict.add(self, key, value)
  494. def poplist(self, key):
  495. buckets = dict.pop(self, key, ())
  496. for bucket in buckets:
  497. bucket.unlink(self)
  498. return [x.value for x in buckets]
  499. def pop(self, key, default=_missing):
  500. try:
  501. buckets = dict.pop(self, key)
  502. except KeyError:
  503. if default is not _missing:
  504. return default
  505. raise exceptions.BadRequestKeyError(key) from None
  506. for bucket in buckets:
  507. bucket.unlink(self)
  508. return buckets[0].value
  509. def popitem(self):
  510. try:
  511. key, buckets = dict.popitem(self)
  512. except KeyError as e:
  513. raise exceptions.BadRequestKeyError(e.args[0]) from None
  514. for bucket in buckets:
  515. bucket.unlink(self)
  516. return key, buckets[0].value
  517. def popitemlist(self):
  518. try:
  519. key, buckets = dict.popitem(self)
  520. except KeyError as e:
  521. raise exceptions.BadRequestKeyError(e.args[0]) from None
  522. for bucket in buckets:
  523. bucket.unlink(self)
  524. return key, [x.value for x in buckets]
  525. class CombinedMultiDict(ImmutableMultiDictMixin, MultiDict):
  526. """A read only :class:`MultiDict` that you can pass multiple :class:`MultiDict`
  527. instances as sequence and it will combine the return values of all wrapped
  528. dicts:
  529. >>> from werkzeug.datastructures import CombinedMultiDict, MultiDict
  530. >>> post = MultiDict([('foo', 'bar')])
  531. >>> get = MultiDict([('blub', 'blah')])
  532. >>> combined = CombinedMultiDict([get, post])
  533. >>> combined['foo']
  534. 'bar'
  535. >>> combined['blub']
  536. 'blah'
  537. This works for all read operations and will raise a `TypeError` for
  538. methods that usually change data which isn't possible.
  539. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
  540. subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
  541. render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP
  542. exceptions.
  543. """
  544. def __reduce_ex__(self, protocol):
  545. return type(self), (self.dicts,)
  546. def __init__(self, dicts=None):
  547. self.dicts = list(dicts) or []
  548. @classmethod
  549. def fromkeys(cls, keys, value=None):
  550. raise TypeError(f"cannot create {cls.__name__!r} instances by fromkeys")
  551. def __getitem__(self, key):
  552. for d in self.dicts:
  553. if key in d:
  554. return d[key]
  555. raise exceptions.BadRequestKeyError(key)
  556. def get(self, key, default=None, type=None):
  557. for d in self.dicts:
  558. if key in d:
  559. if type is not None:
  560. try:
  561. return type(d[key])
  562. except ValueError:
  563. continue
  564. return d[key]
  565. return default
  566. def getlist(self, key, type=None):
  567. rv = []
  568. for d in self.dicts:
  569. rv.extend(d.getlist(key, type))
  570. return rv
  571. def _keys_impl(self):
  572. """This function exists so __len__ can be implemented more efficiently,
  573. saving one list creation from an iterator.
  574. """
  575. rv = set()
  576. rv.update(*self.dicts)
  577. return rv
  578. def keys(self):
  579. return self._keys_impl()
  580. def __iter__(self):
  581. return iter(self.keys())
  582. def items(self, multi=False):
  583. found = set()
  584. for d in self.dicts:
  585. for key, value in d.items(multi):
  586. if multi:
  587. yield key, value
  588. elif key not in found:
  589. found.add(key)
  590. yield key, value
  591. def values(self):
  592. for _key, value in self.items():
  593. yield value
  594. def lists(self):
  595. rv = {}
  596. for d in self.dicts:
  597. for key, values in d.lists():
  598. rv.setdefault(key, []).extend(values)
  599. return list(rv.items())
  600. def listvalues(self):
  601. return (x[1] for x in self.lists())
  602. def copy(self):
  603. """Return a shallow mutable copy of this object.
  604. This returns a :class:`MultiDict` representing the data at the
  605. time of copying. The copy will no longer reflect changes to the
  606. wrapped dicts.
  607. .. versionchanged:: 0.15
  608. Return a mutable :class:`MultiDict`.
  609. """
  610. return MultiDict(self)
  611. def to_dict(self, flat=True):
  612. """Return the contents as regular dict. If `flat` is `True` the
  613. returned dict will only have the first item present, if `flat` is
  614. `False` all values will be returned as lists.
  615. :param flat: If set to `False` the dict returned will have lists
  616. with all the values in it. Otherwise it will only
  617. contain the first item for each key.
  618. :return: a :class:`dict`
  619. """
  620. if flat:
  621. return dict(self.items())
  622. return dict(self.lists())
  623. def __len__(self):
  624. return len(self._keys_impl())
  625. def __contains__(self, key):
  626. for d in self.dicts:
  627. if key in d:
  628. return True
  629. return False
  630. def __repr__(self):
  631. return f"{type(self).__name__}({self.dicts!r})"
  632. class ImmutableDict(ImmutableDictMixin, dict):
  633. """An immutable :class:`dict`.
  634. .. versionadded:: 0.5
  635. """
  636. def __repr__(self):
  637. return f"{type(self).__name__}({dict.__repr__(self)})"
  638. def copy(self):
  639. """Return a shallow mutable copy of this object. Keep in mind that
  640. the standard library's :func:`copy` function is a no-op for this class
  641. like for any other python immutable type (eg: :class:`tuple`).
  642. """
  643. return dict(self)
  644. def __copy__(self):
  645. return self
  646. class ImmutableMultiDict(ImmutableMultiDictMixin, MultiDict):
  647. """An immutable :class:`MultiDict`.
  648. .. versionadded:: 0.5
  649. """
  650. def copy(self):
  651. """Return a shallow mutable copy of this object. Keep in mind that
  652. the standard library's :func:`copy` function is a no-op for this class
  653. like for any other python immutable type (eg: :class:`tuple`).
  654. """
  655. return MultiDict(self)
  656. def __copy__(self):
  657. return self
  658. class ImmutableOrderedMultiDict(ImmutableMultiDictMixin, OrderedMultiDict):
  659. """An immutable :class:`OrderedMultiDict`.
  660. .. versionadded:: 0.6
  661. """
  662. def _iter_hashitems(self):
  663. return enumerate(self.items(multi=True))
  664. def copy(self):
  665. """Return a shallow mutable copy of this object. Keep in mind that
  666. the standard library's :func:`copy` function is a no-op for this class
  667. like for any other python immutable type (eg: :class:`tuple`).
  668. """
  669. return OrderedMultiDict(self)
  670. def __copy__(self):
  671. return self
  672. class CallbackDict(UpdateDictMixin, dict):
  673. """A dict that calls a function passed every time something is changed.
  674. The function is passed the dict instance.
  675. """
  676. def __init__(self, initial=None, on_update=None):
  677. dict.__init__(self, initial or ())
  678. self.on_update = on_update
  679. def __repr__(self):
  680. return f"<{type(self).__name__} {dict.__repr__(self)}>"
  681. class HeaderSet(MutableSet):
  682. """Similar to the :class:`ETags` class this implements a set-like structure.
  683. Unlike :class:`ETags` this is case insensitive and used for vary, allow, and
  684. content-language headers.
  685. If not constructed using the :func:`parse_set_header` function the
  686. instantiation works like this:
  687. >>> hs = HeaderSet(['foo', 'bar', 'baz'])
  688. >>> hs
  689. HeaderSet(['foo', 'bar', 'baz'])
  690. """
  691. def __init__(self, headers=None, on_update=None):
  692. self._headers = list(headers or ())
  693. self._set = {x.lower() for x in self._headers}
  694. self.on_update = on_update
  695. def add(self, header):
  696. """Add a new header to the set."""
  697. self.update((header,))
  698. def remove(self, header):
  699. """Remove a header from the set. This raises an :exc:`KeyError` if the
  700. header is not in the set.
  701. .. versionchanged:: 0.5
  702. In older versions a :exc:`IndexError` was raised instead of a
  703. :exc:`KeyError` if the object was missing.
  704. :param header: the header to be removed.
  705. """
  706. key = header.lower()
  707. if key not in self._set:
  708. raise KeyError(header)
  709. self._set.remove(key)
  710. for idx, key in enumerate(self._headers):
  711. if key.lower() == header:
  712. del self._headers[idx]
  713. break
  714. if self.on_update is not None:
  715. self.on_update(self)
  716. def update(self, iterable):
  717. """Add all the headers from the iterable to the set.
  718. :param iterable: updates the set with the items from the iterable.
  719. """
  720. inserted_any = False
  721. for header in iterable:
  722. key = header.lower()
  723. if key not in self._set:
  724. self._headers.append(header)
  725. self._set.add(key)
  726. inserted_any = True
  727. if inserted_any and self.on_update is not None:
  728. self.on_update(self)
  729. def discard(self, header):
  730. """Like :meth:`remove` but ignores errors.
  731. :param header: the header to be discarded.
  732. """
  733. try:
  734. self.remove(header)
  735. except KeyError:
  736. pass
  737. def find(self, header):
  738. """Return the index of the header in the set or return -1 if not found.
  739. :param header: the header to be looked up.
  740. """
  741. header = header.lower()
  742. for idx, item in enumerate(self._headers):
  743. if item.lower() == header:
  744. return idx
  745. return -1
  746. def index(self, header):
  747. """Return the index of the header in the set or raise an
  748. :exc:`IndexError`.
  749. :param header: the header to be looked up.
  750. """
  751. rv = self.find(header)
  752. if rv < 0:
  753. raise IndexError(header)
  754. return rv
  755. def clear(self):
  756. """Clear the set."""
  757. self._set.clear()
  758. del self._headers[:]
  759. if self.on_update is not None:
  760. self.on_update(self)
  761. def as_set(self, preserve_casing=False):
  762. """Return the set as real python set type. When calling this, all
  763. the items are converted to lowercase and the ordering is lost.
  764. :param preserve_casing: if set to `True` the items in the set returned
  765. will have the original case like in the
  766. :class:`HeaderSet`, otherwise they will
  767. be lowercase.
  768. """
  769. if preserve_casing:
  770. return set(self._headers)
  771. return set(self._set)
  772. def to_header(self):
  773. """Convert the header set into an HTTP header string."""
  774. return ", ".join(map(http.quote_header_value, self._headers))
  775. def __getitem__(self, idx):
  776. return self._headers[idx]
  777. def __delitem__(self, idx):
  778. rv = self._headers.pop(idx)
  779. self._set.remove(rv.lower())
  780. if self.on_update is not None:
  781. self.on_update(self)
  782. def __setitem__(self, idx, value):
  783. old = self._headers[idx]
  784. self._set.remove(old.lower())
  785. self._headers[idx] = value
  786. self._set.add(value.lower())
  787. if self.on_update is not None:
  788. self.on_update(self)
  789. def __contains__(self, header):
  790. return header.lower() in self._set
  791. def __len__(self):
  792. return len(self._set)
  793. def __iter__(self):
  794. return iter(self._headers)
  795. def __bool__(self):
  796. return bool(self._set)
  797. def __str__(self):
  798. return self.to_header()
  799. def __repr__(self):
  800. return f"{type(self).__name__}({self._headers!r})"
  801. # circular dependencies
  802. from .. import http