cavisson-pythonagent 0.0.1__py3-none-any.whl

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