datastructures.py 88 KB

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