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,700 @@
1
+ import warnings
2
+
3
+ from .._compat import integer_types
4
+ from .._compat import string_types
5
+ from .._compat import text_type
6
+ from .._compat import to_bytes
7
+ from .._compat import to_native
8
+ from ..datastructures import Headers
9
+ from ..http import dump_cookie
10
+ from ..http import HTTP_STATUS_CODES
11
+ from ..http import remove_entity_headers
12
+ from ..urls import iri_to_uri
13
+ from ..urls import url_join
14
+ from ..utils import get_content_type
15
+ from ..wsgi import ClosingIterator
16
+ from ..wsgi import get_current_url
17
+
18
+
19
+ def _run_wsgi_app(*args):
20
+ """This function replaces itself to ensure that the test module is not
21
+ imported unless required. DO NOT USE!
22
+ """
23
+ global _run_wsgi_app
24
+ from ..test import run_wsgi_app as _run_wsgi_app
25
+
26
+ return _run_wsgi_app(*args)
27
+
28
+
29
+ def _warn_if_string(iterable):
30
+ """Helper for the response objects to check if the iterable returned
31
+ to the WSGI server is not a string.
32
+ """
33
+ if isinstance(iterable, string_types):
34
+ warnings.warn(
35
+ "Response iterable was set to a string. This will appear to"
36
+ " work but means that the server will send the data to the"
37
+ " client one character at a time. This is almost never"
38
+ " intended behavior, use 'response.data' to assign strings"
39
+ " to the response object.",
40
+ stacklevel=2,
41
+ )
42
+
43
+
44
+ def _iter_encoded(iterable, charset):
45
+ for item in iterable:
46
+ if isinstance(item, text_type):
47
+ yield item.encode(charset)
48
+ else:
49
+ yield item
50
+
51
+
52
+ def _clean_accept_ranges(accept_ranges):
53
+ if accept_ranges is True:
54
+ return "bytes"
55
+ elif accept_ranges is False:
56
+ return "none"
57
+ elif isinstance(accept_ranges, text_type):
58
+ return to_native(accept_ranges)
59
+ raise ValueError("Invalid accept_ranges value")
60
+
61
+
62
+ class BaseResponse(object):
63
+ """Base response class. The most important fact about a response object
64
+ is that it's a regular WSGI application. It's initialized with a couple
65
+ of response parameters (headers, body, status code etc.) and will start a
66
+ valid WSGI response when called with the environ and start response
67
+ callable.
68
+
69
+ Because it's a WSGI application itself processing usually ends before the
70
+ actual response is sent to the server. This helps debugging systems
71
+ because they can catch all the exceptions before responses are started.
72
+
73
+ Here a small example WSGI application that takes advantage of the
74
+ response objects::
75
+
76
+ from pythonagent.vendor.werkzeug.wrappers import BaseResponse as Response
77
+
78
+ def index():
79
+ return Response('Index page')
80
+
81
+ def application(environ, start_response):
82
+ path = environ.get('PATH_INFO') or '/'
83
+ if path == '/':
84
+ response = index()
85
+ else:
86
+ response = Response('Not Found', status=404)
87
+ return response(environ, start_response)
88
+
89
+ Like :class:`BaseRequest` which object is lacking a lot of functionality
90
+ implemented in mixins. This gives you a better control about the actual
91
+ API of your response objects, so you can create subclasses and add custom
92
+ functionality. A full featured response object is available as
93
+ :class:`Response` which implements a couple of useful mixins.
94
+
95
+ To enforce a new type of already existing responses you can use the
96
+ :meth:`force_type` method. This is useful if you're working with different
97
+ subclasses of response objects and you want to post process them with a
98
+ known interface.
99
+
100
+ Per default the response object will assume all the text data is `utf-8`
101
+ encoded. Please refer to :doc:`the unicode chapter </unicode>` for more
102
+ details about customizing the behavior.
103
+
104
+ Response can be any kind of iterable or string. If it's a string it's
105
+ considered being an iterable with one item which is the string passed.
106
+ Headers can be a list of tuples or a
107
+ :class:`~werkzeug.datastructures.Headers` object.
108
+
109
+ Special note for `mimetype` and `content_type`: For most mime types
110
+ `mimetype` and `content_type` work the same, the difference affects
111
+ only 'text' mimetypes. If the mimetype passed with `mimetype` is a
112
+ mimetype starting with `text/`, the charset parameter of the response
113
+ object is appended to it. In contrast the `content_type` parameter is
114
+ always added as header unmodified.
115
+
116
+ .. versionchanged:: 0.5
117
+ the `direct_passthrough` parameter was added.
118
+
119
+ :param response: a string or response iterable.
120
+ :param status: a string with a status or an integer with the status code.
121
+ :param headers: a list of headers or a
122
+ :class:`~werkzeug.datastructures.Headers` object.
123
+ :param mimetype: the mimetype for the response. See notice above.
124
+ :param content_type: the content type for the response. See notice above.
125
+ :param direct_passthrough: if set to `True` :meth:`iter_encoded` is not
126
+ called before iteration which makes it
127
+ possible to pass special iterators through
128
+ unchanged (see :func:`wrap_file` for more
129
+ details.)
130
+ """
131
+
132
+ #: the charset of the response.
133
+ charset = "utf-8"
134
+
135
+ #: the default status if none is provided.
136
+ default_status = 200
137
+
138
+ #: the default mimetype if none is provided.
139
+ default_mimetype = "text/plain"
140
+
141
+ #: if set to `False` accessing properties on the response object will
142
+ #: not try to consume the response iterator and convert it into a list.
143
+ #:
144
+ #: .. versionadded:: 0.6.2
145
+ #:
146
+ #: That attribute was previously called `implicit_seqence_conversion`.
147
+ #: (Notice the typo). If you did use this feature, you have to adapt
148
+ #: your code to the name change.
149
+ implicit_sequence_conversion = True
150
+
151
+ #: Should this response object correct the location header to be RFC
152
+ #: conformant? This is true by default.
153
+ #:
154
+ #: .. versionadded:: 0.8
155
+ autocorrect_location_header = True
156
+
157
+ #: Should this response object automatically set the content-length
158
+ #: header if possible? This is true by default.
159
+ #:
160
+ #: .. versionadded:: 0.8
161
+ automatically_set_content_length = True
162
+
163
+ #: Warn if a cookie header exceeds this size. The default, 4093, should be
164
+ #: safely `supported by most browsers <cookie_>`_. A cookie larger than
165
+ #: this size will still be sent, but it may be ignored or handled
166
+ #: incorrectly by some browsers. Set to 0 to disable this check.
167
+ #:
168
+ #: .. versionadded:: 0.13
169
+ #:
170
+ #: .. _`cookie`: http://browsercookielimits.squawky.net/
171
+ max_cookie_size = 4093
172
+
173
+ def __init__(
174
+ self,
175
+ response=None,
176
+ status=None,
177
+ headers=None,
178
+ mimetype=None,
179
+ content_type=None,
180
+ direct_passthrough=False,
181
+ ):
182
+ if isinstance(headers, Headers):
183
+ self.headers = headers
184
+ elif not headers:
185
+ self.headers = Headers()
186
+ else:
187
+ self.headers = Headers(headers)
188
+
189
+ if content_type is None:
190
+ if mimetype is None and "content-type" not in self.headers:
191
+ mimetype = self.default_mimetype
192
+ if mimetype is not None:
193
+ mimetype = get_content_type(mimetype, self.charset)
194
+ content_type = mimetype
195
+ if content_type is not None:
196
+ self.headers["Content-Type"] = content_type
197
+ if status is None:
198
+ status = self.default_status
199
+ if isinstance(status, integer_types):
200
+ self.status_code = status
201
+ else:
202
+ self.status = status
203
+
204
+ self.direct_passthrough = direct_passthrough
205
+ self._on_close = []
206
+
207
+ # we set the response after the headers so that if a class changes
208
+ # the charset attribute, the data is set in the correct charset.
209
+ if response is None:
210
+ self.response = []
211
+ elif isinstance(response, (text_type, bytes, bytearray)):
212
+ self.set_data(response)
213
+ else:
214
+ self.response = response
215
+
216
+ def call_on_close(self, func):
217
+ """Adds a function to the internal list of functions that should
218
+ be called as part of closing down the response. Since 0.7 this
219
+ function also returns the function that was passed so that this
220
+ can be used as a decorator.
221
+
222
+ .. versionadded:: 0.6
223
+ """
224
+ self._on_close.append(func)
225
+ return func
226
+
227
+ def __repr__(self):
228
+ if self.is_sequence:
229
+ body_info = "%d bytes" % sum(map(len, self.iter_encoded()))
230
+ else:
231
+ body_info = "streamed" if self.is_streamed else "likely-streamed"
232
+ return "<%s %s [%s]>" % (self.__class__.__name__, body_info, self.status)
233
+
234
+ @classmethod
235
+ def force_type(cls, response, environ=None):
236
+ """Enforce that the WSGI response is a response object of the current
237
+ type. Werkzeug will use the :class:`BaseResponse` internally in many
238
+ situations like the exceptions. If you call :meth:`get_response` on an
239
+ exception you will get back a regular :class:`BaseResponse` object, even
240
+ if you are using a custom subclass.
241
+
242
+ This method can enforce a given response type, and it will also
243
+ convert arbitrary WSGI callables into response objects if an environ
244
+ is provided::
245
+
246
+ # convert a Werkzeug response object into an instance of the
247
+ # MyResponseClass subclass.
248
+ response = MyResponseClass.force_type(response)
249
+
250
+ # convert any WSGI application into a response object
251
+ response = MyResponseClass.force_type(response, environ)
252
+
253
+ This is especially useful if you want to post-process responses in
254
+ the main dispatcher and use functionality provided by your subclass.
255
+
256
+ Keep in mind that this will modify response objects in place if
257
+ possible!
258
+
259
+ :param response: a response object or wsgi application.
260
+ :param environ: a WSGI environment object.
261
+ :return: a response object.
262
+ """
263
+ if not isinstance(response, BaseResponse):
264
+ if environ is None:
265
+ raise TypeError(
266
+ "cannot convert WSGI application into response"
267
+ " objects without an environ"
268
+ )
269
+ response = BaseResponse(*_run_wsgi_app(response, environ))
270
+ response.__class__ = cls
271
+ return response
272
+
273
+ @classmethod
274
+ def from_app(cls, app, environ, buffered=False):
275
+ """Create a new response object from an application output. This
276
+ works best if you pass it an application that returns a generator all
277
+ the time. Sometimes applications may use the `write()` callable
278
+ returned by the `start_response` function. This tries to resolve such
279
+ edge cases automatically. But if you don't get the expected output
280
+ you should set `buffered` to `True` which enforces buffering.
281
+
282
+ :param app: the WSGI application to execute.
283
+ :param environ: the WSGI environment to execute against.
284
+ :param buffered: set to `True` to enforce buffering.
285
+ :return: a response object.
286
+ """
287
+ return cls(*_run_wsgi_app(app, environ, buffered))
288
+
289
+ @property
290
+ def status_code(self):
291
+ """The HTTP status code as a number."""
292
+ return self._status_code
293
+
294
+ @status_code.setter
295
+ def status_code(self, code):
296
+ self._status_code = code
297
+ try:
298
+ self._status = "%d %s" % (code, HTTP_STATUS_CODES[code].upper())
299
+ except KeyError:
300
+ self._status = "%d UNKNOWN" % code
301
+
302
+ @property
303
+ def status(self):
304
+ """The HTTP status code as a string."""
305
+ return self._status
306
+
307
+ @status.setter
308
+ def status(self, value):
309
+ try:
310
+ self._status = to_native(value)
311
+ except AttributeError:
312
+ raise TypeError("Invalid status argument")
313
+
314
+ try:
315
+ self._status_code = int(self._status.split(None, 1)[0])
316
+ except ValueError:
317
+ self._status_code = 0
318
+ self._status = "0 %s" % self._status
319
+ except IndexError:
320
+ raise ValueError("Empty status argument")
321
+
322
+ def get_data(self, as_text=False):
323
+ """The string representation of the request body. Whenever you call
324
+ this property the request iterable is encoded and flattened. This
325
+ can lead to unwanted behavior if you stream big data.
326
+
327
+ This behavior can be disabled by setting
328
+ :attr:`implicit_sequence_conversion` to `False`.
329
+
330
+ If `as_text` is set to `True` the return value will be a decoded
331
+ unicode string.
332
+
333
+ .. versionadded:: 0.9
334
+ """
335
+ self._ensure_sequence()
336
+ rv = b"".join(self.iter_encoded())
337
+ if as_text:
338
+ rv = rv.decode(self.charset)
339
+ return rv
340
+
341
+ def set_data(self, value):
342
+ """Sets a new string as response. The value set must be either a
343
+ unicode or bytestring. If a unicode string is set it's encoded
344
+ automatically to the charset of the response (utf-8 by default).
345
+
346
+ .. versionadded:: 0.9
347
+ """
348
+ # if an unicode string is set, it's encoded directly so that we
349
+ # can set the content length
350
+ if isinstance(value, text_type):
351
+ value = value.encode(self.charset)
352
+ else:
353
+ value = bytes(value)
354
+ self.response = [value]
355
+ if self.automatically_set_content_length:
356
+ self.headers["Content-Length"] = str(len(value))
357
+
358
+ data = property(
359
+ get_data,
360
+ set_data,
361
+ doc="A descriptor that calls :meth:`get_data` and :meth:`set_data`.",
362
+ )
363
+
364
+ def calculate_content_length(self):
365
+ """Returns the content length if available or `None` otherwise."""
366
+ try:
367
+ self._ensure_sequence()
368
+ except RuntimeError:
369
+ return None
370
+ return sum(len(x) for x in self.iter_encoded())
371
+
372
+ def _ensure_sequence(self, mutable=False):
373
+ """This method can be called by methods that need a sequence. If
374
+ `mutable` is true, it will also ensure that the response sequence
375
+ is a standard Python list.
376
+
377
+ .. versionadded:: 0.6
378
+ """
379
+ if self.is_sequence:
380
+ # if we need a mutable object, we ensure it's a list.
381
+ if mutable and not isinstance(self.response, list):
382
+ self.response = list(self.response)
383
+ return
384
+ if self.direct_passthrough:
385
+ raise RuntimeError(
386
+ "Attempted implicit sequence conversion but the"
387
+ " response object is in direct passthrough mode."
388
+ )
389
+ if not self.implicit_sequence_conversion:
390
+ raise RuntimeError(
391
+ "The response object required the iterable to be a"
392
+ " sequence, but the implicit conversion was disabled."
393
+ " Call make_sequence() yourself."
394
+ )
395
+ self.make_sequence()
396
+
397
+ def make_sequence(self):
398
+ """Converts the response iterator in a list. By default this happens
399
+ automatically if required. If `implicit_sequence_conversion` is
400
+ disabled, this method is not automatically called and some properties
401
+ might raise exceptions. This also encodes all the items.
402
+
403
+ .. versionadded:: 0.6
404
+ """
405
+ if not self.is_sequence:
406
+ # if we consume an iterable we have to ensure that the close
407
+ # method of the iterable is called if available when we tear
408
+ # down the response
409
+ close = getattr(self.response, "close", None)
410
+ self.response = list(self.iter_encoded())
411
+ if close is not None:
412
+ self.call_on_close(close)
413
+
414
+ def iter_encoded(self):
415
+ """Iter the response encoded with the encoding of the response.
416
+ If the response object is invoked as WSGI application the return
417
+ value of this method is used as application iterator unless
418
+ :attr:`direct_passthrough` was activated.
419
+ """
420
+ if __debug__:
421
+ _warn_if_string(self.response)
422
+ # Encode in a separate function so that self.response is fetched
423
+ # early. This allows us to wrap the response with the return
424
+ # value from get_app_iter or iter_encoded.
425
+ return _iter_encoded(self.response, self.charset)
426
+
427
+ def set_cookie(
428
+ self,
429
+ key,
430
+ value="",
431
+ max_age=None,
432
+ expires=None,
433
+ path="/",
434
+ domain=None,
435
+ secure=False,
436
+ httponly=False,
437
+ samesite=None,
438
+ ):
439
+ """Sets a cookie. The parameters are the same as in the cookie `Morsel`
440
+ object in the Python standard library but it accepts unicode data, too.
441
+
442
+ A warning is raised if the size of the cookie header exceeds
443
+ :attr:`max_cookie_size`, but the header will still be set.
444
+
445
+ :param key: the key (name) of the cookie to be set.
446
+ :param value: the value of the cookie.
447
+ :param max_age: should be a number of seconds, or `None` (default) if
448
+ the cookie should last only as long as the client's
449
+ browser session.
450
+ :param expires: should be a `datetime` object or UNIX timestamp.
451
+ :param path: limits the cookie to a given path, per default it will
452
+ span the whole domain.
453
+ :param domain: if you want to set a cross-domain cookie. For example,
454
+ ``domain=".example.com"`` will set a cookie that is
455
+ readable by the domain ``www.example.com``,
456
+ ``foo.example.com`` etc. Otherwise, a cookie will only
457
+ be readable by the domain that set it.
458
+ :param secure: If `True`, the cookie will only be available via HTTPS
459
+ :param httponly: disallow JavaScript to access the cookie. This is an
460
+ extension to the cookie standard and probably not
461
+ supported by all browsers.
462
+ :param samesite: Limits the scope of the cookie such that it will only
463
+ be attached to requests if those requests are
464
+ "same-site".
465
+ """
466
+ self.headers.add(
467
+ "Set-Cookie",
468
+ dump_cookie(
469
+ key,
470
+ value=value,
471
+ max_age=max_age,
472
+ expires=expires,
473
+ path=path,
474
+ domain=domain,
475
+ secure=secure,
476
+ httponly=httponly,
477
+ charset=self.charset,
478
+ max_size=self.max_cookie_size,
479
+ samesite=samesite,
480
+ ),
481
+ )
482
+
483
+ def delete_cookie(self, key, path="/", domain=None):
484
+ """Delete a cookie. Fails silently if key doesn't exist.
485
+
486
+ :param key: the key (name) of the cookie to be deleted.
487
+ :param path: if the cookie that should be deleted was limited to a
488
+ path, the path has to be defined here.
489
+ :param domain: if the cookie that should be deleted was limited to a
490
+ domain, that domain has to be defined here.
491
+ """
492
+ self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
493
+
494
+ @property
495
+ def is_streamed(self):
496
+ """If the response is streamed (the response is not an iterable with
497
+ a length information) this property is `True`. In this case streamed
498
+ means that there is no information about the number of iterations.
499
+ This is usually `True` if a generator is passed to the response object.
500
+
501
+ This is useful for checking before applying some sort of post
502
+ filtering that should not take place for streamed responses.
503
+ """
504
+ try:
505
+ len(self.response)
506
+ except (TypeError, AttributeError):
507
+ return True
508
+ return False
509
+
510
+ @property
511
+ def is_sequence(self):
512
+ """If the iterator is buffered, this property will be `True`. A
513
+ response object will consider an iterator to be buffered if the
514
+ response attribute is a list or tuple.
515
+
516
+ .. versionadded:: 0.6
517
+ """
518
+ return isinstance(self.response, (tuple, list))
519
+
520
+ def close(self):
521
+ """Close the wrapped response if possible. You can also use the object
522
+ in a with statement which will automatically close it.
523
+
524
+ .. versionadded:: 0.9
525
+ Can now be used in a with statement.
526
+ """
527
+ if hasattr(self.response, "close"):
528
+ self.response.close()
529
+ for func in self._on_close:
530
+ func()
531
+
532
+ def __enter__(self):
533
+ return self
534
+
535
+ def __exit__(self, exc_type, exc_value, tb):
536
+ self.close()
537
+
538
+ def freeze(self):
539
+ """Call this method if you want to make your response object ready for
540
+ being pickled. This buffers the generator if there is one. It will
541
+ also set the `Content-Length` header to the length of the body.
542
+
543
+ .. versionchanged:: 0.6
544
+ The `Content-Length` header is now set.
545
+ """
546
+ # we explicitly set the length to a list of the *encoded* response
547
+ # iterator. Even if the implicit sequence conversion is disabled.
548
+ self.response = list(self.iter_encoded())
549
+ self.headers["Content-Length"] = str(sum(map(len, self.response)))
550
+
551
+ def get_wsgi_headers(self, environ):
552
+ """This is automatically called right before the response is started
553
+ and returns headers modified for the given environment. It returns a
554
+ copy of the headers from the response with some modifications applied
555
+ if necessary.
556
+
557
+ For example the location header (if present) is joined with the root
558
+ URL of the environment. Also the content length is automatically set
559
+ to zero here for certain status codes.
560
+
561
+ .. versionchanged:: 0.6
562
+ Previously that function was called `fix_headers` and modified
563
+ the response object in place. Also since 0.6, IRIs in location
564
+ and content-location headers are handled properly.
565
+
566
+ Also starting with 0.6, Werkzeug will attempt to set the content
567
+ length if it is able to figure it out on its own. This is the
568
+ case if all the strings in the response iterable are already
569
+ encoded and the iterable is buffered.
570
+
571
+ :param environ: the WSGI environment of the request.
572
+ :return: returns a new :class:`~werkzeug.datastructures.Headers`
573
+ object.
574
+ """
575
+ headers = Headers(self.headers)
576
+ location = None
577
+ content_location = None
578
+ content_length = None
579
+ status = self.status_code
580
+
581
+ # iterate over the headers to find all values in one go. Because
582
+ # get_wsgi_headers is used each response that gives us a tiny
583
+ # speedup.
584
+ for key, value in headers:
585
+ ikey = key.lower()
586
+ if ikey == u"location":
587
+ location = value
588
+ elif ikey == u"content-location":
589
+ content_location = value
590
+ elif ikey == u"content-length":
591
+ content_length = value
592
+
593
+ # make sure the location header is an absolute URL
594
+ if location is not None:
595
+ old_location = location
596
+ if isinstance(location, text_type):
597
+ # Safe conversion is necessary here as we might redirect
598
+ # to a broken URI scheme (for instance itms-services).
599
+ location = iri_to_uri(location, safe_conversion=True)
600
+
601
+ if self.autocorrect_location_header:
602
+ current_url = get_current_url(environ, strip_querystring=True)
603
+ if isinstance(current_url, text_type):
604
+ current_url = iri_to_uri(current_url)
605
+ location = url_join(current_url, location)
606
+ if location != old_location:
607
+ headers["Location"] = location
608
+
609
+ # make sure the content location is a URL
610
+ if content_location is not None and isinstance(content_location, text_type):
611
+ headers["Content-Location"] = iri_to_uri(content_location)
612
+
613
+ if 100 <= status < 200 or status == 204:
614
+ # Per section 3.3.2 of RFC 7230, "a server MUST NOT send a
615
+ # Content-Length header field in any response with a status
616
+ # code of 1xx (Informational) or 204 (No Content)."
617
+ headers.remove("Content-Length")
618
+ elif status == 304:
619
+ remove_entity_headers(headers)
620
+
621
+ # if we can determine the content length automatically, we
622
+ # should try to do that. But only if this does not involve
623
+ # flattening the iterator or encoding of unicode strings in
624
+ # the response. We however should not do that if we have a 304
625
+ # response.
626
+ if (
627
+ self.automatically_set_content_length
628
+ and self.is_sequence
629
+ and content_length is None
630
+ and status not in (204, 304)
631
+ and not (100 <= status < 200)
632
+ ):
633
+ try:
634
+ content_length = sum(len(to_bytes(x, "ascii")) for x in self.response)
635
+ except UnicodeError:
636
+ # aha, something non-bytestringy in there, too bad, we
637
+ # can't safely figure out the length of the response.
638
+ pass
639
+ else:
640
+ headers["Content-Length"] = str(content_length)
641
+
642
+ return headers
643
+
644
+ def get_app_iter(self, environ):
645
+ """Returns the application iterator for the given environ. Depending
646
+ on the request method and the current status code the return value
647
+ might be an empty response rather than the one from the response.
648
+
649
+ If the request method is `HEAD` or the status code is in a range
650
+ where the HTTP specification requires an empty response, an empty
651
+ iterable is returned.
652
+
653
+ .. versionadded:: 0.6
654
+
655
+ :param environ: the WSGI environment of the request.
656
+ :return: a response iterable.
657
+ """
658
+ status = self.status_code
659
+ if (
660
+ environ["REQUEST_METHOD"] == "HEAD"
661
+ or 100 <= status < 200
662
+ or status in (204, 304)
663
+ ):
664
+ iterable = ()
665
+ elif self.direct_passthrough:
666
+ if __debug__:
667
+ _warn_if_string(self.response)
668
+ return self.response
669
+ else:
670
+ iterable = self.iter_encoded()
671
+ return ClosingIterator(iterable, self.close)
672
+
673
+ def get_wsgi_response(self, environ):
674
+ """Returns the final WSGI response as tuple. The first item in
675
+ the tuple is the application iterator, the second the status and
676
+ the third the list of headers. The response returned is created
677
+ specially for the given environment. For example if the request
678
+ method in the WSGI environment is ``'HEAD'`` the response will
679
+ be empty and only the headers and status code will be present.
680
+
681
+ .. versionadded:: 0.6
682
+
683
+ :param environ: the WSGI environment of the request.
684
+ :return: an ``(app_iter, status, headers)`` tuple.
685
+ """
686
+ headers = self.get_wsgi_headers(environ)
687
+ app_iter = self.get_app_iter(environ)
688
+ return app_iter, self.status, headers.to_wsgi_list()
689
+
690
+ def __call__(self, environ, start_response):
691
+ """Process this response as WSGI application.
692
+
693
+ :param environ: the WSGI environment.
694
+ :param start_response: the response callable provided by the WSGI
695
+ server.
696
+ :return: an application iterator
697
+ """
698
+ app_iter, status, headers = self.get_wsgi_response(environ)
699
+ start_response(status, headers)
700
+ return app_iter