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,778 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ werkzeug.utils
4
+ ~~~~~~~~~~~~~~
5
+
6
+ This module implements various utilities for WSGI applications. Most of
7
+ them are used by the request and response wrappers but especially for
8
+ middleware development it makes sense to use them without the wrappers.
9
+
10
+ :copyright: 2007 Pallets
11
+ :license: BSD-3-Clause
12
+ """
13
+ import codecs
14
+ import os
15
+ import pkgutil
16
+ import re
17
+ import sys
18
+
19
+ from ._compat import iteritems
20
+ from ._compat import PY2
21
+ from ._compat import reraise
22
+ from ._compat import string_types
23
+ from ._compat import text_type
24
+ from ._compat import unichr
25
+ from ._internal import _DictAccessorProperty
26
+ from ._internal import _missing
27
+ from ._internal import _parse_signature
28
+
29
+ try:
30
+ from html.entities import name2codepoint
31
+ except ImportError:
32
+ from htmlentitydefs import name2codepoint
33
+
34
+
35
+ _format_re = re.compile(r"\$(?:(%s)|\{(%s)\})" % (("[a-zA-Z_][a-zA-Z0-9_]*",) * 2))
36
+ _entity_re = re.compile(r"&([^;]+);")
37
+ _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")
38
+ _windows_device_files = (
39
+ "CON",
40
+ "AUX",
41
+ "COM1",
42
+ "COM2",
43
+ "COM3",
44
+ "COM4",
45
+ "LPT1",
46
+ "LPT2",
47
+ "LPT3",
48
+ "PRN",
49
+ "NUL",
50
+ )
51
+
52
+
53
+ class cached_property(property):
54
+ """A decorator that converts a function into a lazy property. The
55
+ function wrapped is called the first time to retrieve the result
56
+ and then that calculated result is used the next time you access
57
+ the value::
58
+
59
+ class Foo(object):
60
+
61
+ @cached_property
62
+ def foo(self):
63
+ # calculate something important here
64
+ return 42
65
+
66
+ The class has to have a `__dict__` in order for this property to
67
+ work.
68
+ """
69
+
70
+ # implementation detail: A subclass of python's builtin property
71
+ # decorator, we override __get__ to check for a cached value. If one
72
+ # chooses to invoke __get__ by hand the property will still work as
73
+ # expected because the lookup logic is replicated in __get__ for
74
+ # manual invocation.
75
+
76
+ def __init__(self, func, name=None, doc=None):
77
+ self.__name__ = name or func.__name__
78
+ self.__module__ = func.__module__
79
+ self.__doc__ = doc or func.__doc__
80
+ self.func = func
81
+
82
+ def __set__(self, obj, value):
83
+ obj.__dict__[self.__name__] = value
84
+
85
+ def __get__(self, obj, type=None):
86
+ if obj is None:
87
+ return self
88
+ value = obj.__dict__.get(self.__name__, _missing)
89
+ if value is _missing:
90
+ value = self.func(obj)
91
+ obj.__dict__[self.__name__] = value
92
+ return value
93
+
94
+
95
+ def invalidate_cached_property(obj, name):
96
+ """Invalidates the cache for a :class:`cached_property`:
97
+
98
+ >>> class Test(object):
99
+ ... @cached_property
100
+ ... def magic_number(self):
101
+ ... print("recalculating...")
102
+ ... return 42
103
+ ...
104
+ >>> var = Test()
105
+ >>> var.magic_number
106
+ recalculating...
107
+ 42
108
+ >>> var.magic_number
109
+ 42
110
+ >>> invalidate_cached_property(var, "magic_number")
111
+ >>> var.magic_number
112
+ recalculating...
113
+ 42
114
+
115
+ You must pass the name of the cached property as the second argument.
116
+ """
117
+ if not isinstance(getattr(obj.__class__, name, None), cached_property):
118
+ raise TypeError(
119
+ "Attribute {} of object {} is not a cached_property, "
120
+ "cannot be invalidated".format(name, obj)
121
+ )
122
+ obj.__dict__[name] = _missing
123
+
124
+
125
+ class environ_property(_DictAccessorProperty):
126
+ """Maps request attributes to environment variables. This works not only
127
+ for the Werzeug request object, but also any other class with an
128
+ environ attribute:
129
+
130
+ >>> class Test(object):
131
+ ... environ = {'key': 'value'}
132
+ ... test = environ_property('key')
133
+ >>> var = Test()
134
+ >>> var.test
135
+ 'value'
136
+
137
+ If you pass it a second value it's used as default if the key does not
138
+ exist, the third one can be a converter that takes a value and converts
139
+ it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value
140
+ is used. If no default value is provided `None` is used.
141
+
142
+ Per default the property is read only. You have to explicitly enable it
143
+ by passing ``read_only=False`` to the constructor.
144
+ """
145
+
146
+ read_only = True
147
+
148
+ def lookup(self, obj):
149
+ return obj.environ
150
+
151
+
152
+ class header_property(_DictAccessorProperty):
153
+ """Like `environ_property` but for headers."""
154
+
155
+ def lookup(self, obj):
156
+ return obj.headers
157
+
158
+
159
+ class HTMLBuilder(object):
160
+ """Helper object for HTML generation.
161
+
162
+ Per default there are two instances of that class. The `html` one, and
163
+ the `xhtml` one for those two dialects. The class uses keyword parameters
164
+ and positional parameters to generate small snippets of HTML.
165
+
166
+ Keyword parameters are converted to XML/SGML attributes, positional
167
+ arguments are used as children. Because Python accepts positional
168
+ arguments before keyword arguments it's a good idea to use a list with the
169
+ star-syntax for some children:
170
+
171
+ >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
172
+ ... html.a('bar', href='bar.html')])
173
+ u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'
174
+
175
+ This class works around some browser limitations and can not be used for
176
+ arbitrary SGML/XML generation. For that purpose lxml and similar
177
+ libraries exist.
178
+
179
+ Calling the builder escapes the string passed:
180
+
181
+ >>> html.p(html("<foo>"))
182
+ u'<p>&lt;foo&gt;</p>'
183
+ """
184
+
185
+ _entity_re = re.compile(r"&([^;]+);")
186
+ _entities = name2codepoint.copy()
187
+ _entities["apos"] = 39
188
+ _empty_elements = {
189
+ "area",
190
+ "base",
191
+ "basefont",
192
+ "br",
193
+ "col",
194
+ "command",
195
+ "embed",
196
+ "frame",
197
+ "hr",
198
+ "img",
199
+ "input",
200
+ "keygen",
201
+ "isindex",
202
+ "link",
203
+ "meta",
204
+ "param",
205
+ "source",
206
+ "wbr",
207
+ }
208
+ _boolean_attributes = {
209
+ "selected",
210
+ "checked",
211
+ "compact",
212
+ "declare",
213
+ "defer",
214
+ "disabled",
215
+ "ismap",
216
+ "multiple",
217
+ "nohref",
218
+ "noresize",
219
+ "noshade",
220
+ "nowrap",
221
+ }
222
+ _plaintext_elements = {"textarea"}
223
+ _c_like_cdata = {"script", "style"}
224
+
225
+ def __init__(self, dialect):
226
+ self._dialect = dialect
227
+
228
+ def __call__(self, s):
229
+ return escape(s)
230
+
231
+ def __getattr__(self, tag):
232
+ if tag[:2] == "__":
233
+ raise AttributeError(tag)
234
+
235
+ def proxy(*children, **arguments):
236
+ buffer = "<" + tag
237
+ for key, value in iteritems(arguments):
238
+ if value is None:
239
+ continue
240
+ if key[-1] == "_":
241
+ key = key[:-1]
242
+ if key in self._boolean_attributes:
243
+ if not value:
244
+ continue
245
+ if self._dialect == "xhtml":
246
+ value = '="' + key + '"'
247
+ else:
248
+ value = ""
249
+ else:
250
+ value = '="' + escape(value) + '"'
251
+ buffer += " " + key + value
252
+ if not children and tag in self._empty_elements:
253
+ if self._dialect == "xhtml":
254
+ buffer += " />"
255
+ else:
256
+ buffer += ">"
257
+ return buffer
258
+ buffer += ">"
259
+
260
+ children_as_string = "".join(
261
+ [text_type(x) for x in children if x is not None]
262
+ )
263
+
264
+ if children_as_string:
265
+ if tag in self._plaintext_elements:
266
+ children_as_string = escape(children_as_string)
267
+ elif tag in self._c_like_cdata and self._dialect == "xhtml":
268
+ children_as_string = (
269
+ "/*<![CDATA[*/" + children_as_string + "/*]]>*/"
270
+ )
271
+ buffer += children_as_string + "</" + tag + ">"
272
+ return buffer
273
+
274
+ return proxy
275
+
276
+ def __repr__(self):
277
+ return "<%s for %r>" % (self.__class__.__name__, self._dialect)
278
+
279
+
280
+ html = HTMLBuilder("html")
281
+ xhtml = HTMLBuilder("xhtml")
282
+
283
+ # https://cgit.freedesktop.org/xdg/shared-mime-info/tree/freedesktop.org.xml.in
284
+ # https://www.iana.org/assignments/media-types/media-types.xhtml
285
+ # Types listed in the XDG mime info that have a charset in the IANA registration.
286
+ _charset_mimetypes = {
287
+ "application/ecmascript",
288
+ "application/javascript",
289
+ "application/sql",
290
+ "application/xml",
291
+ "application/xml-dtd",
292
+ "application/xml-external-parsed-entity",
293
+ }
294
+
295
+
296
+ def get_content_type(mimetype, charset):
297
+ """Returns the full content type string with charset for a mimetype.
298
+
299
+ If the mimetype represents text, the charset parameter will be
300
+ appended, otherwise the mimetype is returned unchanged.
301
+
302
+ :param mimetype: The mimetype to be used as content type.
303
+ :param charset: The charset to be appended for text mimetypes.
304
+ :return: The content type.
305
+
306
+ .. versionchanged:: 0.15
307
+ Any type that ends with ``+xml`` gets a charset, not just those
308
+ that start with ``application/``. Known text types such as
309
+ ``application/javascript`` are also given charsets.
310
+ """
311
+ if (
312
+ mimetype.startswith("text/")
313
+ or mimetype in _charset_mimetypes
314
+ or mimetype.endswith("+xml")
315
+ ):
316
+ mimetype += "; charset=" + charset
317
+
318
+ return mimetype
319
+
320
+
321
+ def detect_utf_encoding(data):
322
+ """Detect which UTF encoding was used to encode the given bytes.
323
+
324
+ The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
325
+ accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
326
+ or little endian. Some editors or libraries may prepend a BOM.
327
+
328
+ :internal:
329
+
330
+ :param data: Bytes in unknown UTF encoding.
331
+ :return: UTF encoding name
332
+
333
+ .. versionadded:: 0.15
334
+ """
335
+ head = data[:4]
336
+
337
+ if head[:3] == codecs.BOM_UTF8:
338
+ return "utf-8-sig"
339
+
340
+ if b"\x00" not in head:
341
+ return "utf-8"
342
+
343
+ if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):
344
+ return "utf-32"
345
+
346
+ if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):
347
+ return "utf-16"
348
+
349
+ if len(head) == 4:
350
+ if head[:3] == b"\x00\x00\x00":
351
+ return "utf-32-be"
352
+
353
+ if head[::2] == b"\x00\x00":
354
+ return "utf-16-be"
355
+
356
+ if head[1:] == b"\x00\x00\x00":
357
+ return "utf-32-le"
358
+
359
+ if head[1::2] == b"\x00\x00":
360
+ return "utf-16-le"
361
+
362
+ if len(head) == 2:
363
+ return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"
364
+
365
+ return "utf-8"
366
+
367
+
368
+ def format_string(string, context):
369
+ """String-template format a string:
370
+
371
+ >>> format_string('$foo and ${foo}s', dict(foo=42))
372
+ '42 and 42s'
373
+
374
+ This does not do any attribute lookup etc. For more advanced string
375
+ formattings have a look at the `werkzeug.template` module.
376
+
377
+ :param string: the format string.
378
+ :param context: a dict with the variables to insert.
379
+ """
380
+
381
+ def lookup_arg(match):
382
+ x = context[match.group(1) or match.group(2)]
383
+ if not isinstance(x, string_types):
384
+ x = type(string)(x)
385
+ return x
386
+
387
+ return _format_re.sub(lookup_arg, string)
388
+
389
+
390
+ def secure_filename(filename):
391
+ r"""Pass it a filename and it will return a secure version of it. This
392
+ filename can then safely be stored on a regular file system and passed
393
+ to :func:`os.path.join`. The filename returned is an ASCII only string
394
+ for maximum portability.
395
+
396
+ On windows systems the function also makes sure that the file is not
397
+ named after one of the special device files.
398
+
399
+ >>> secure_filename("My cool movie.mov")
400
+ 'My_cool_movie.mov'
401
+ >>> secure_filename("../../../etc/passwd")
402
+ 'etc_passwd'
403
+ >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
404
+ 'i_contain_cool_umlauts.txt'
405
+
406
+ The function might return an empty filename. It's your responsibility
407
+ to ensure that the filename is unique and that you abort or
408
+ generate a random filename if the function returned an empty one.
409
+
410
+ .. versionadded:: 0.5
411
+
412
+ :param filename: the filename to secure
413
+ """
414
+ if isinstance(filename, text_type):
415
+ from unicodedata import normalize
416
+
417
+ filename = normalize("NFKD", filename).encode("ascii", "ignore")
418
+ if not PY2:
419
+ filename = filename.decode("ascii")
420
+ for sep in os.path.sep, os.path.altsep:
421
+ if sep:
422
+ filename = filename.replace(sep, " ")
423
+ filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip(
424
+ "._"
425
+ )
426
+
427
+ # on nt a couple of special files are present in each folder. We
428
+ # have to ensure that the target file is not such a filename. In
429
+ # this case we prepend an underline
430
+ if (
431
+ os.name == "nt"
432
+ and filename
433
+ and filename.split(".")[0].upper() in _windows_device_files
434
+ ):
435
+ filename = "_" + filename
436
+
437
+ return filename
438
+
439
+
440
+ def escape(s):
441
+ """Replace special characters "&", "<", ">" and (") to HTML-safe sequences.
442
+
443
+ There is a special handling for `None` which escapes to an empty string.
444
+
445
+ .. versionchanged:: 0.9
446
+ `quote` is now implicitly on.
447
+
448
+ :param s: the string to escape.
449
+ :param quote: ignored.
450
+ """
451
+ if s is None:
452
+ return ""
453
+ elif hasattr(s, "__html__"):
454
+ return text_type(s.__html__())
455
+
456
+ if not isinstance(s, string_types):
457
+ s = text_type(s)
458
+
459
+ return (
460
+ s.replace("&", "&amp;")
461
+ .replace("<", "&lt;")
462
+ .replace(">", "&gt;")
463
+ .replace('"', "&quot;")
464
+ )
465
+
466
+
467
+ def unescape(s):
468
+ """The reverse function of `escape`. This unescapes all the HTML
469
+ entities, not only the XML entities inserted by `escape`.
470
+
471
+ :param s: the string to unescape.
472
+ """
473
+
474
+ def handle_match(m):
475
+ name = m.group(1)
476
+ if name in HTMLBuilder._entities:
477
+ return unichr(HTMLBuilder._entities[name])
478
+ try:
479
+ if name[:2] in ("#x", "#X"):
480
+ return unichr(int(name[2:], 16))
481
+ elif name.startswith("#"):
482
+ return unichr(int(name[1:]))
483
+ except ValueError:
484
+ pass
485
+ return u""
486
+
487
+ return _entity_re.sub(handle_match, s)
488
+
489
+
490
+ def redirect(location, code=302, Response=None):
491
+ """Returns a response object (a WSGI application) that, if called,
492
+ redirects the client to the target location. Supported codes are
493
+ 301, 302, 303, 305, 307, and 308. 300 is not supported because
494
+ it's not a real redirect and 304 because it's the answer for a
495
+ request with a request with defined If-Modified-Since headers.
496
+
497
+ .. versionadded:: 0.6
498
+ The location can now be a unicode string that is encoded using
499
+ the :func:`iri_to_uri` function.
500
+
501
+ .. versionadded:: 0.10
502
+ The class used for the Response object can now be passed in.
503
+
504
+ :param location: the location the response should redirect to.
505
+ :param code: the redirect status code. defaults to 302.
506
+ :param class Response: a Response class to use when instantiating a
507
+ response. The default is :class:`werkzeug.wrappers.Response` if
508
+ unspecified.
509
+ """
510
+ if Response is None:
511
+ from .wrappers import Response
512
+
513
+ display_location = escape(location)
514
+ if isinstance(location, text_type):
515
+ # Safe conversion is necessary here as we might redirect
516
+ # to a broken URI scheme (for instance itms-services).
517
+ from .urls import iri_to_uri
518
+
519
+ location = iri_to_uri(location, safe_conversion=True)
520
+ response = Response(
521
+ '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
522
+ "<title>Redirecting...</title>\n"
523
+ "<h1>Redirecting...</h1>\n"
524
+ "<p>You should be redirected automatically to target URL: "
525
+ '<a href="%s">%s</a>. If not click the link.'
526
+ % (escape(location), display_location),
527
+ code,
528
+ mimetype="text/html",
529
+ )
530
+ response.headers["Location"] = location
531
+ return response
532
+
533
+
534
+ def append_slash_redirect(environ, code=301):
535
+ """Redirects to the same URL but with a slash appended. The behavior
536
+ of this function is undefined if the path ends with a slash already.
537
+
538
+ :param environ: the WSGI environment for the request that triggers
539
+ the redirect.
540
+ :param code: the status code for the redirect.
541
+ """
542
+ new_path = environ["PATH_INFO"].strip("/") + "/"
543
+ query_string = environ.get("QUERY_STRING")
544
+ if query_string:
545
+ new_path += "?" + query_string
546
+ return redirect(new_path, code)
547
+
548
+
549
+ def import_string(import_name, silent=False):
550
+ """Imports an object based on a string. This is useful if you want to
551
+ use import paths as endpoints or something similar. An import path can
552
+ be specified either in dotted notation (``xml.sax.saxutils.escape``)
553
+ or with a colon as object delimiter (``xml.sax.saxutils:escape``).
554
+
555
+ If `silent` is True the return value will be `None` if the import fails.
556
+
557
+ :param import_name: the dotted name for the object to import.
558
+ :param silent: if set to `True` import errors are ignored and
559
+ `None` is returned instead.
560
+ :return: imported object
561
+ """
562
+ # force the import name to automatically convert to strings
563
+ # __import__ is not able to handle unicode strings in the fromlist
564
+ # if the module is a package
565
+ import_name = str(import_name).replace(":", ".")
566
+ try:
567
+ try:
568
+ __import__(import_name)
569
+ except ImportError:
570
+ if "." not in import_name:
571
+ raise
572
+ else:
573
+ return sys.modules[import_name]
574
+
575
+ module_name, obj_name = import_name.rsplit(".", 1)
576
+ module = __import__(module_name, globals(), locals(), [obj_name])
577
+ try:
578
+ return getattr(module, obj_name)
579
+ except AttributeError as e:
580
+ raise ImportError(e)
581
+
582
+ except ImportError as e:
583
+ if not silent:
584
+ reraise(
585
+ ImportStringError, ImportStringError(import_name, e), sys.exc_info()[2]
586
+ )
587
+
588
+
589
+ def find_modules(import_path, include_packages=False, recursive=False):
590
+ """Finds all the modules below a package. This can be useful to
591
+ automatically import all views / controllers so that their metaclasses /
592
+ function decorators have a chance to register themselves on the
593
+ application.
594
+
595
+ Packages are not returned unless `include_packages` is `True`. This can
596
+ also recursively list modules but in that case it will import all the
597
+ packages to get the correct load path of that module.
598
+
599
+ :param import_path: the dotted name for the package to find child modules.
600
+ :param include_packages: set to `True` if packages should be returned, too.
601
+ :param recursive: set to `True` if recursion should happen.
602
+ :return: generator
603
+ """
604
+ module = import_string(import_path)
605
+ path = getattr(module, "__path__", None)
606
+ if path is None:
607
+ raise ValueError("%r is not a package" % import_path)
608
+ basename = module.__name__ + "."
609
+ for _importer, modname, ispkg in pkgutil.iter_modules(path):
610
+ modname = basename + modname
611
+ if ispkg:
612
+ if include_packages:
613
+ yield modname
614
+ if recursive:
615
+ for item in find_modules(modname, include_packages, True):
616
+ yield item
617
+ else:
618
+ yield modname
619
+
620
+
621
+ def validate_arguments(func, args, kwargs, drop_extra=True):
622
+ """Checks if the function accepts the arguments and keyword arguments.
623
+ Returns a new ``(args, kwargs)`` tuple that can safely be passed to
624
+ the function without causing a `TypeError` because the function signature
625
+ is incompatible. If `drop_extra` is set to `True` (which is the default)
626
+ any extra positional or keyword arguments are dropped automatically.
627
+
628
+ The exception raised provides three attributes:
629
+
630
+ `missing`
631
+ A set of argument names that the function expected but where
632
+ missing.
633
+
634
+ `extra`
635
+ A dict of keyword arguments that the function can not handle but
636
+ where provided.
637
+
638
+ `extra_positional`
639
+ A list of values that where given by positional argument but the
640
+ function cannot accept.
641
+
642
+ This can be useful for decorators that forward user submitted data to
643
+ a view function::
644
+
645
+ from pythonagent.vendor.werkzeug.utils import ArgumentValidationError, validate_arguments
646
+
647
+ def sanitize(f):
648
+ def proxy(request):
649
+ data = request.values.to_dict()
650
+ try:
651
+ args, kwargs = validate_arguments(f, (request,), data)
652
+ except ArgumentValidationError:
653
+ raise BadRequest('The browser failed to transmit all '
654
+ 'the data expected.')
655
+ return f(*args, **kwargs)
656
+ return proxy
657
+
658
+ :param func: the function the validation is performed against.
659
+ :param args: a tuple of positional arguments.
660
+ :param kwargs: a dict of keyword arguments.
661
+ :param drop_extra: set to `False` if you don't want extra arguments
662
+ to be silently dropped.
663
+ :return: tuple in the form ``(args, kwargs)``.
664
+ """
665
+ parser = _parse_signature(func)
666
+ args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5]
667
+ if missing:
668
+ raise ArgumentValidationError(tuple(missing))
669
+ elif (extra or extra_positional) and not drop_extra:
670
+ raise ArgumentValidationError(None, extra, extra_positional)
671
+ return tuple(args), kwargs
672
+
673
+
674
+ def bind_arguments(func, args, kwargs):
675
+ """Bind the arguments provided into a dict. When passed a function,
676
+ a tuple of arguments and a dict of keyword arguments `bind_arguments`
677
+ returns a dict of names as the function would see it. This can be useful
678
+ to implement a cache decorator that uses the function arguments to build
679
+ the cache key based on the values of the arguments.
680
+
681
+ :param func: the function the arguments should be bound for.
682
+ :param args: tuple of positional arguments.
683
+ :param kwargs: a dict of keyword arguments.
684
+ :return: a :class:`dict` of bound keyword arguments.
685
+ """
686
+ (
687
+ args,
688
+ kwargs,
689
+ missing,
690
+ extra,
691
+ extra_positional,
692
+ arg_spec,
693
+ vararg_var,
694
+ kwarg_var,
695
+ ) = _parse_signature(func)(args, kwargs)
696
+ values = {}
697
+ for (name, _has_default, _default), value in zip(arg_spec, args):
698
+ values[name] = value
699
+ if vararg_var is not None:
700
+ values[vararg_var] = tuple(extra_positional)
701
+ elif extra_positional:
702
+ raise TypeError("too many positional arguments")
703
+ if kwarg_var is not None:
704
+ multikw = set(extra) & set([x[0] for x in arg_spec])
705
+ if multikw:
706
+ raise TypeError(
707
+ "got multiple values for keyword argument " + repr(next(iter(multikw)))
708
+ )
709
+ values[kwarg_var] = extra
710
+ elif extra:
711
+ raise TypeError("got unexpected keyword argument " + repr(next(iter(extra))))
712
+ return values
713
+
714
+
715
+ class ArgumentValidationError(ValueError):
716
+
717
+ """Raised if :func:`validate_arguments` fails to validate"""
718
+
719
+ def __init__(self, missing=None, extra=None, extra_positional=None):
720
+ self.missing = set(missing or ())
721
+ self.extra = extra or {}
722
+ self.extra_positional = extra_positional or []
723
+ ValueError.__init__(
724
+ self,
725
+ "function arguments invalid. (%d missing, %d additional)"
726
+ % (len(self.missing), len(self.extra) + len(self.extra_positional)),
727
+ )
728
+
729
+
730
+ class ImportStringError(ImportError):
731
+ """Provides information about a failed :func:`import_string` attempt."""
732
+
733
+ #: String in dotted notation that failed to be imported.
734
+ import_name = None
735
+ #: Wrapped exception.
736
+ exception = None
737
+
738
+ def __init__(self, import_name, exception):
739
+ self.import_name = import_name
740
+ self.exception = exception
741
+
742
+ msg = (
743
+ "import_string() failed for %r. Possible reasons are:\n\n"
744
+ "- missing __init__.py in a package;\n"
745
+ "- package or module path not included in sys.path;\n"
746
+ "- duplicated package or module name taking precedence in "
747
+ "sys.path;\n"
748
+ "- missing module, class, function or variable;\n\n"
749
+ "Debugged import:\n\n%s\n\n"
750
+ "Original exception:\n\n%s: %s"
751
+ )
752
+
753
+ name = ""
754
+ tracked = []
755
+ for part in import_name.replace(":", ".").split("."):
756
+ name += (name and ".") + part
757
+ imported = import_string(name, silent=True)
758
+ if imported:
759
+ tracked.append((name, getattr(imported, "__file__", None)))
760
+ else:
761
+ track = ["- %r found in %r." % (n, i) for n, i in tracked]
762
+ track.append("- %r not found." % name)
763
+ msg = msg % (
764
+ import_name,
765
+ "\n".join(track),
766
+ exception.__class__.__name__,
767
+ str(exception),
768
+ )
769
+ break
770
+
771
+ ImportError.__init__(self, msg)
772
+
773
+ def __repr__(self):
774
+ return "<%s(%r, %r)>" % (
775
+ self.__class__.__name__,
776
+ self.import_name,
777
+ self.exception,
778
+ )