datastructures.py 85 KB

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