datastructures.py 96 KB

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