datastructures.py 95 KB

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