datastructures.py 88 KB

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