datastructures.py 90 KB

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