datastructures.py 98 KB

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