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,1000 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ werkzeug.wsgi
4
+ ~~~~~~~~~~~~~
5
+
6
+ This module implements WSGI related helpers.
7
+
8
+ :copyright: 2007 Pallets
9
+ :license: BSD-3-Clause
10
+ """
11
+ import io
12
+ import re
13
+ from functools import partial
14
+ from functools import update_wrapper
15
+ from itertools import chain
16
+
17
+ from ._compat import BytesIO
18
+ from ._compat import implements_iterator
19
+ from ._compat import make_literal_wrapper
20
+ from ._compat import string_types
21
+ from ._compat import text_type
22
+ from ._compat import to_bytes
23
+ from ._compat import to_unicode
24
+ from ._compat import try_coerce_native
25
+ from ._compat import wsgi_get_bytes
26
+ from ._internal import _encode_idna
27
+ from .urls import uri_to_iri
28
+ from .urls import url_join
29
+ from .urls import url_parse
30
+ from .urls import url_quote
31
+
32
+
33
+ def responder(f):
34
+ """Marks a function as responder. Decorate a function with it and it
35
+ will automatically call the return value as WSGI application.
36
+
37
+ Example::
38
+
39
+ @responder
40
+ def application(environ, start_response):
41
+ return Response('Hello World!')
42
+ """
43
+ return update_wrapper(lambda *a: f(*a)(*a[-2:]), f)
44
+
45
+
46
+ def get_current_url(
47
+ environ,
48
+ root_only=False,
49
+ strip_querystring=False,
50
+ host_only=False,
51
+ trusted_hosts=None,
52
+ ):
53
+ """A handy helper function that recreates the full URL as IRI for the
54
+ current request or parts of it. Here's an example:
55
+
56
+ >>> from werkzeug.test import create_environ
57
+ >>> env = create_environ("/?param=foo", "http://localhost/script")
58
+ >>> get_current_url(env)
59
+ 'http://localhost/script/?param=foo'
60
+ >>> get_current_url(env, root_only=True)
61
+ 'http://localhost/script/'
62
+ >>> get_current_url(env, host_only=True)
63
+ 'http://localhost/'
64
+ >>> get_current_url(env, strip_querystring=True)
65
+ 'http://localhost/script/'
66
+
67
+ This optionally it verifies that the host is in a list of trusted hosts.
68
+ If the host is not in there it will raise a
69
+ :exc:`~werkzeug.exceptions.SecurityError`.
70
+
71
+ Note that the string returned might contain unicode characters as the
72
+ representation is an IRI not an URI. If you need an ASCII only
73
+ representation you can use the :func:`~werkzeug.urls.iri_to_uri`
74
+ function:
75
+
76
+ >>> from werkzeug.urls import iri_to_uri
77
+ >>> iri_to_uri(get_current_url(env))
78
+ 'http://localhost/script/?param=foo'
79
+
80
+ :param environ: the WSGI environment to get the current URL from.
81
+ :param root_only: set `True` if you only want the root URL.
82
+ :param strip_querystring: set to `True` if you don't want the querystring.
83
+ :param host_only: set to `True` if the host URL should be returned.
84
+ :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
85
+ for more information.
86
+ """
87
+ tmp = [environ["wsgi.url_scheme"], "://", get_host(environ, trusted_hosts)]
88
+ cat = tmp.append
89
+ if host_only:
90
+ return uri_to_iri("".join(tmp) + "/")
91
+ cat(url_quote(wsgi_get_bytes(environ.get("SCRIPT_NAME", ""))).rstrip("/"))
92
+ cat("/")
93
+ if not root_only:
94
+ cat(url_quote(wsgi_get_bytes(environ.get("PATH_INFO", "")).lstrip(b"/")))
95
+ if not strip_querystring:
96
+ qs = get_query_string(environ)
97
+ if qs:
98
+ cat("?" + qs)
99
+ return uri_to_iri("".join(tmp))
100
+
101
+
102
+ def host_is_trusted(hostname, trusted_list):
103
+ """Checks if a host is trusted against a list. This also takes care
104
+ of port normalization.
105
+
106
+ .. versionadded:: 0.9
107
+
108
+ :param hostname: the hostname to check
109
+ :param trusted_list: a list of hostnames to check against. If a
110
+ hostname starts with a dot it will match against
111
+ all subdomains as well.
112
+ """
113
+ if not hostname:
114
+ return False
115
+
116
+ if isinstance(trusted_list, string_types):
117
+ trusted_list = [trusted_list]
118
+
119
+ def _normalize(hostname):
120
+ if ":" in hostname:
121
+ hostname = hostname.rsplit(":", 1)[0]
122
+ return _encode_idna(hostname)
123
+
124
+ try:
125
+ hostname = _normalize(hostname)
126
+ except UnicodeError:
127
+ return False
128
+ for ref in trusted_list:
129
+ if ref.startswith("."):
130
+ ref = ref[1:]
131
+ suffix_match = True
132
+ else:
133
+ suffix_match = False
134
+ try:
135
+ ref = _normalize(ref)
136
+ except UnicodeError:
137
+ return False
138
+ if ref == hostname:
139
+ return True
140
+ if suffix_match and hostname.endswith(b"." + ref):
141
+ return True
142
+ return False
143
+
144
+
145
+ def get_host(environ, trusted_hosts=None):
146
+ """Return the host for the given WSGI environment. This first checks
147
+ the ``Host`` header. If it's not present, then ``SERVER_NAME`` and
148
+ ``SERVER_PORT`` are used. The host will only contain the port if it
149
+ is different than the standard port for the protocol.
150
+
151
+ Optionally, verify that the host is trusted using
152
+ :func:`host_is_trusted` and raise a
153
+ :exc:`~werkzeug.exceptions.SecurityError` if it is not.
154
+
155
+ :param environ: The WSGI environment to get the host from.
156
+ :param trusted_hosts: A list of trusted hosts.
157
+ :return: Host, with port if necessary.
158
+ :raise ~werkzeug.exceptions.SecurityError: If the host is not
159
+ trusted.
160
+ """
161
+ if "HTTP_HOST" in environ:
162
+ rv = environ["HTTP_HOST"]
163
+ if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
164
+ rv = rv[:-3]
165
+ elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
166
+ rv = rv[:-4]
167
+ else:
168
+ rv = environ["SERVER_NAME"]
169
+ if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (
170
+ ("https", "443"),
171
+ ("http", "80"),
172
+ ):
173
+ rv += ":" + environ["SERVER_PORT"]
174
+ if trusted_hosts is not None:
175
+ if not host_is_trusted(rv, trusted_hosts):
176
+ from .exceptions import SecurityError
177
+
178
+ raise SecurityError('Host "%s" is not trusted' % rv)
179
+ return rv
180
+
181
+
182
+ def get_content_length(environ):
183
+ """Returns the content length from the WSGI environment as
184
+ integer. If it's not available or chunked transfer encoding is used,
185
+ ``None`` is returned.
186
+
187
+ .. versionadded:: 0.9
188
+
189
+ :param environ: the WSGI environ to fetch the content length from.
190
+ """
191
+ if environ.get("HTTP_TRANSFER_ENCODING", "") == "chunked":
192
+ return None
193
+
194
+ content_length = environ.get("CONTENT_LENGTH")
195
+ if content_length is not None:
196
+ try:
197
+ return max(0, int(content_length))
198
+ except (ValueError, TypeError):
199
+ pass
200
+
201
+
202
+ def get_input_stream(environ, safe_fallback=True):
203
+ """Returns the input stream from the WSGI environment and wraps it
204
+ in the most sensible way possible. The stream returned is not the
205
+ raw WSGI stream in most cases but one that is safe to read from
206
+ without taking into account the content length.
207
+
208
+ If content length is not set, the stream will be empty for safety reasons.
209
+ If the WSGI server supports chunked or infinite streams, it should set
210
+ the ``wsgi.input_terminated`` value in the WSGI environ to indicate that.
211
+
212
+ .. versionadded:: 0.9
213
+
214
+ :param environ: the WSGI environ to fetch the stream from.
215
+ :param safe_fallback: use an empty stream as a safe fallback when the
216
+ content length is not set. Disabling this allows infinite streams,
217
+ which can be a denial-of-service risk.
218
+ """
219
+ stream = environ["wsgi.input"]
220
+ content_length = get_content_length(environ)
221
+
222
+ # A wsgi extension that tells us if the input is terminated. In
223
+ # that case we return the stream unchanged as we know we can safely
224
+ # read it until the end.
225
+ if environ.get("wsgi.input_terminated"):
226
+ return stream
227
+
228
+ # If the request doesn't specify a content length, returning the stream is
229
+ # potentially dangerous because it could be infinite, malicious or not. If
230
+ # safe_fallback is true, return an empty stream instead for safety.
231
+ if content_length is None:
232
+ return BytesIO() if safe_fallback else stream
233
+
234
+ # Otherwise limit the stream to the content length
235
+ return LimitedStream(stream, content_length)
236
+
237
+
238
+ def get_query_string(environ):
239
+ """Returns the `QUERY_STRING` from the WSGI environment. This also takes
240
+ care about the WSGI decoding dance on Python 3 environments as a
241
+ native string. The string returned will be restricted to ASCII
242
+ characters.
243
+
244
+ .. versionadded:: 0.9
245
+
246
+ :param environ: the WSGI environment object to get the query string from.
247
+ """
248
+ qs = wsgi_get_bytes(environ.get("QUERY_STRING", ""))
249
+ # QUERY_STRING really should be ascii safe but some browsers
250
+ # will send us some unicode stuff (I am looking at you IE).
251
+ # In that case we want to urllib quote it badly.
252
+ return try_coerce_native(url_quote(qs, safe=":&%=+$!*'(),"))
253
+
254
+
255
+ def get_path_info(environ, charset="utf-8", errors="replace"):
256
+ """Returns the `PATH_INFO` from the WSGI environment and properly
257
+ decodes it. This also takes care about the WSGI decoding dance
258
+ on Python 3 environments. if the `charset` is set to `None` a
259
+ bytestring is returned.
260
+
261
+ .. versionadded:: 0.9
262
+
263
+ :param environ: the WSGI environment object to get the path from.
264
+ :param charset: the charset for the path info, or `None` if no
265
+ decoding should be performed.
266
+ :param errors: the decoding error handling.
267
+ """
268
+ path = wsgi_get_bytes(environ.get("PATH_INFO", ""))
269
+ return to_unicode(path, charset, errors, allow_none_charset=True)
270
+
271
+
272
+ def get_script_name(environ, charset="utf-8", errors="replace"):
273
+ """Returns the `SCRIPT_NAME` from the WSGI environment and properly
274
+ decodes it. This also takes care about the WSGI decoding dance
275
+ on Python 3 environments. if the `charset` is set to `None` a
276
+ bytestring is returned.
277
+
278
+ .. versionadded:: 0.9
279
+
280
+ :param environ: the WSGI environment object to get the path from.
281
+ :param charset: the charset for the path, or `None` if no
282
+ decoding should be performed.
283
+ :param errors: the decoding error handling.
284
+ """
285
+ path = wsgi_get_bytes(environ.get("SCRIPT_NAME", ""))
286
+ return to_unicode(path, charset, errors, allow_none_charset=True)
287
+
288
+
289
+ def pop_path_info(environ, charset="utf-8", errors="replace"):
290
+ """Removes and returns the next segment of `PATH_INFO`, pushing it onto
291
+ `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
292
+
293
+ If the `charset` is set to `None` a bytestring is returned.
294
+
295
+ If there are empty segments (``'/foo//bar``) these are ignored but
296
+ properly pushed to the `SCRIPT_NAME`:
297
+
298
+ >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
299
+ >>> pop_path_info(env)
300
+ 'a'
301
+ >>> env['SCRIPT_NAME']
302
+ '/foo/a'
303
+ >>> pop_path_info(env)
304
+ 'b'
305
+ >>> env['SCRIPT_NAME']
306
+ '/foo/a/b'
307
+
308
+ .. versionadded:: 0.5
309
+
310
+ .. versionchanged:: 0.9
311
+ The path is now decoded and a charset and encoding
312
+ parameter can be provided.
313
+
314
+ :param environ: the WSGI environment that is modified.
315
+ """
316
+ path = environ.get("PATH_INFO")
317
+ if not path:
318
+ return None
319
+
320
+ script_name = environ.get("SCRIPT_NAME", "")
321
+
322
+ # shift multiple leading slashes over
323
+ old_path = path
324
+ path = path.lstrip("/")
325
+ if path != old_path:
326
+ script_name += "/" * (len(old_path) - len(path))
327
+
328
+ if "/" not in path:
329
+ environ["PATH_INFO"] = ""
330
+ environ["SCRIPT_NAME"] = script_name + path
331
+ rv = wsgi_get_bytes(path)
332
+ else:
333
+ segment, path = path.split("/", 1)
334
+ environ["PATH_INFO"] = "/" + path
335
+ environ["SCRIPT_NAME"] = script_name + segment
336
+ rv = wsgi_get_bytes(segment)
337
+
338
+ return to_unicode(rv, charset, errors, allow_none_charset=True)
339
+
340
+
341
+ def peek_path_info(environ, charset="utf-8", errors="replace"):
342
+ """Returns the next segment on the `PATH_INFO` or `None` if there
343
+ is none. Works like :func:`pop_path_info` without modifying the
344
+ environment:
345
+
346
+ >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
347
+ >>> peek_path_info(env)
348
+ 'a'
349
+ >>> peek_path_info(env)
350
+ 'a'
351
+
352
+ If the `charset` is set to `None` a bytestring is returned.
353
+
354
+ .. versionadded:: 0.5
355
+
356
+ .. versionchanged:: 0.9
357
+ The path is now decoded and a charset and encoding
358
+ parameter can be provided.
359
+
360
+ :param environ: the WSGI environment that is checked.
361
+ """
362
+ segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)
363
+ if segments:
364
+ return to_unicode(
365
+ wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True
366
+ )
367
+
368
+
369
+ def extract_path_info(
370
+ environ_or_baseurl,
371
+ path_or_url,
372
+ charset="utf-8",
373
+ errors="werkzeug.url_quote",
374
+ collapse_http_schemes=True,
375
+ ):
376
+ """Extracts the path info from the given URL (or WSGI environment) and
377
+ path. The path info returned is a unicode string, not a bytestring
378
+ suitable for a WSGI environment. The URLs might also be IRIs.
379
+
380
+ If the path info could not be determined, `None` is returned.
381
+
382
+ Some examples:
383
+
384
+ >>> extract_path_info('http://example.com/app', '/app/hello')
385
+ u'/hello'
386
+ >>> extract_path_info('http://example.com/app',
387
+ ... 'https://example.com/app/hello')
388
+ u'/hello'
389
+ >>> extract_path_info('http://example.com/app',
390
+ ... 'https://example.com/app/hello',
391
+ ... collapse_http_schemes=False) is None
392
+ True
393
+
394
+ Instead of providing a base URL you can also pass a WSGI environment.
395
+
396
+ :param environ_or_baseurl: a WSGI environment dict, a base URL or
397
+ base IRI. This is the root of the
398
+ application.
399
+ :param path_or_url: an absolute path from the server root, a
400
+ relative path (in which case it's the path info)
401
+ or a full URL. Also accepts IRIs and unicode
402
+ parameters.
403
+ :param charset: the charset for byte data in URLs
404
+ :param errors: the error handling on decode
405
+ :param collapse_http_schemes: if set to `False` the algorithm does
406
+ not assume that http and https on the
407
+ same server point to the same
408
+ resource.
409
+
410
+ .. versionchanged:: 0.15
411
+ The ``errors`` parameter defaults to leaving invalid bytes
412
+ quoted instead of replacing them.
413
+
414
+ .. versionadded:: 0.6
415
+ """
416
+
417
+ def _normalize_netloc(scheme, netloc):
418
+ parts = netloc.split(u"@", 1)[-1].split(u":", 1)
419
+ if len(parts) == 2:
420
+ netloc, port = parts
421
+ if (scheme == u"http" and port == u"80") or (
422
+ scheme == u"https" and port == u"443"
423
+ ):
424
+ port = None
425
+ else:
426
+ netloc = parts[0]
427
+ port = None
428
+ if port is not None:
429
+ netloc += u":" + port
430
+ return netloc
431
+
432
+ # make sure whatever we are working on is a IRI and parse it
433
+ path = uri_to_iri(path_or_url, charset, errors)
434
+ if isinstance(environ_or_baseurl, dict):
435
+ environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True)
436
+ base_iri = uri_to_iri(environ_or_baseurl, charset, errors)
437
+ base_scheme, base_netloc, base_path = url_parse(base_iri)[:3]
438
+ cur_scheme, cur_netloc, cur_path, = url_parse(url_join(base_iri, path))[:3]
439
+
440
+ # normalize the network location
441
+ base_netloc = _normalize_netloc(base_scheme, base_netloc)
442
+ cur_netloc = _normalize_netloc(cur_scheme, cur_netloc)
443
+
444
+ # is that IRI even on a known HTTP scheme?
445
+ if collapse_http_schemes:
446
+ for scheme in base_scheme, cur_scheme:
447
+ if scheme not in (u"http", u"https"):
448
+ return None
449
+ else:
450
+ if not (base_scheme in (u"http", u"https") and base_scheme == cur_scheme):
451
+ return None
452
+
453
+ # are the netlocs compatible?
454
+ if base_netloc != cur_netloc:
455
+ return None
456
+
457
+ # are we below the application path?
458
+ base_path = base_path.rstrip(u"/")
459
+ if not cur_path.startswith(base_path):
460
+ return None
461
+
462
+ return u"/" + cur_path[len(base_path) :].lstrip(u"/")
463
+
464
+
465
+ @implements_iterator
466
+ class ClosingIterator(object):
467
+ """The WSGI specification requires that all middlewares and gateways
468
+ respect the `close` callback of the iterable returned by the application.
469
+ Because it is useful to add another close action to a returned iterable
470
+ and adding a custom iterable is a boring task this class can be used for
471
+ that::
472
+
473
+ return ClosingIterator(app(environ, start_response), [cleanup_session,
474
+ cleanup_locals])
475
+
476
+ If there is just one close function it can be passed instead of the list.
477
+
478
+ A closing iterator is not needed if the application uses response objects
479
+ and finishes the processing if the response is started::
480
+
481
+ try:
482
+ return response(environ, start_response)
483
+ finally:
484
+ cleanup_session()
485
+ cleanup_locals()
486
+ """
487
+
488
+ def __init__(self, iterable, callbacks=None):
489
+ iterator = iter(iterable)
490
+ self._next = partial(next, iterator)
491
+ if callbacks is None:
492
+ callbacks = []
493
+ elif callable(callbacks):
494
+ callbacks = [callbacks]
495
+ else:
496
+ callbacks = list(callbacks)
497
+ iterable_close = getattr(iterable, "close", None)
498
+ if iterable_close:
499
+ callbacks.insert(0, iterable_close)
500
+ self._callbacks = callbacks
501
+
502
+ def __iter__(self):
503
+ return self
504
+
505
+ def __next__(self):
506
+ return self._next()
507
+
508
+ def close(self):
509
+ for callback in self._callbacks:
510
+ callback()
511
+
512
+
513
+ def wrap_file(environ, file, buffer_size=8192):
514
+ """Wraps a file. This uses the WSGI server's file wrapper if available
515
+ or otherwise the generic :class:`FileWrapper`.
516
+
517
+ .. versionadded:: 0.5
518
+
519
+ If the file wrapper from the WSGI server is used it's important to not
520
+ iterate over it from inside the application but to pass it through
521
+ unchanged. If you want to pass out a file wrapper inside a response
522
+ object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`.
523
+
524
+ More information about file wrappers are available in :pep:`333`.
525
+
526
+ :param file: a :class:`file`-like object with a :meth:`~file.read` method.
527
+ :param buffer_size: number of bytes for one iteration.
528
+ """
529
+ return environ.get("wsgi.file_wrapper", FileWrapper)(file, buffer_size)
530
+
531
+
532
+ @implements_iterator
533
+ class FileWrapper(object):
534
+ """This class can be used to convert a :class:`file`-like object into
535
+ an iterable. It yields `buffer_size` blocks until the file is fully
536
+ read.
537
+
538
+ You should not use this class directly but rather use the
539
+ :func:`wrap_file` function that uses the WSGI server's file wrapper
540
+ support if it's available.
541
+
542
+ .. versionadded:: 0.5
543
+
544
+ If you're using this object together with a :class:`BaseResponse` you have
545
+ to use the `direct_passthrough` mode.
546
+
547
+ :param file: a :class:`file`-like object with a :meth:`~file.read` method.
548
+ :param buffer_size: number of bytes for one iteration.
549
+ """
550
+
551
+ def __init__(self, file, buffer_size=8192):
552
+ self.file = file
553
+ self.buffer_size = buffer_size
554
+
555
+ def close(self):
556
+ if hasattr(self.file, "close"):
557
+ self.file.close()
558
+
559
+ def seekable(self):
560
+ if hasattr(self.file, "seekable"):
561
+ return self.file.seekable()
562
+ if hasattr(self.file, "seek"):
563
+ return True
564
+ return False
565
+
566
+ def seek(self, *args):
567
+ if hasattr(self.file, "seek"):
568
+ self.file.seek(*args)
569
+
570
+ def tell(self):
571
+ if hasattr(self.file, "tell"):
572
+ return self.file.tell()
573
+ return None
574
+
575
+ def __iter__(self):
576
+ return self
577
+
578
+ def __next__(self):
579
+ data = self.file.read(self.buffer_size)
580
+ if data:
581
+ return data
582
+ raise StopIteration()
583
+
584
+
585
+ @implements_iterator
586
+ class _RangeWrapper(object):
587
+ # private for now, but should we make it public in the future ?
588
+
589
+ """This class can be used to convert an iterable object into
590
+ an iterable that will only yield a piece of the underlying content.
591
+ It yields blocks until the underlying stream range is fully read.
592
+ The yielded blocks will have a size that can't exceed the original
593
+ iterator defined block size, but that can be smaller.
594
+
595
+ If you're using this object together with a :class:`BaseResponse` you have
596
+ to use the `direct_passthrough` mode.
597
+
598
+ :param iterable: an iterable object with a :meth:`__next__` method.
599
+ :param start_byte: byte from which read will start.
600
+ :param byte_range: how many bytes to read.
601
+ """
602
+
603
+ def __init__(self, iterable, start_byte=0, byte_range=None):
604
+ self.iterable = iter(iterable)
605
+ self.byte_range = byte_range
606
+ self.start_byte = start_byte
607
+ self.end_byte = None
608
+ if byte_range is not None:
609
+ self.end_byte = self.start_byte + self.byte_range
610
+ self.read_length = 0
611
+ self.seekable = hasattr(iterable, "seekable") and iterable.seekable()
612
+ self.end_reached = False
613
+
614
+ def __iter__(self):
615
+ return self
616
+
617
+ def _next_chunk(self):
618
+ try:
619
+ chunk = next(self.iterable)
620
+ self.read_length += len(chunk)
621
+ return chunk
622
+ except StopIteration:
623
+ self.end_reached = True
624
+ raise
625
+
626
+ def _first_iteration(self):
627
+ chunk = None
628
+ if self.seekable:
629
+ self.iterable.seek(self.start_byte)
630
+ self.read_length = self.iterable.tell()
631
+ contextual_read_length = self.read_length
632
+ else:
633
+ while self.read_length <= self.start_byte:
634
+ chunk = self._next_chunk()
635
+ if chunk is not None:
636
+ chunk = chunk[self.start_byte - self.read_length :]
637
+ contextual_read_length = self.start_byte
638
+ return chunk, contextual_read_length
639
+
640
+ def _next(self):
641
+ if self.end_reached:
642
+ raise StopIteration()
643
+ chunk = None
644
+ contextual_read_length = self.read_length
645
+ if self.read_length == 0:
646
+ chunk, contextual_read_length = self._first_iteration()
647
+ if chunk is None:
648
+ chunk = self._next_chunk()
649
+ if self.end_byte is not None and self.read_length >= self.end_byte:
650
+ self.end_reached = True
651
+ return chunk[: self.end_byte - contextual_read_length]
652
+ return chunk
653
+
654
+ def __next__(self):
655
+ chunk = self._next()
656
+ if chunk:
657
+ return chunk
658
+ self.end_reached = True
659
+ raise StopIteration()
660
+
661
+ def close(self):
662
+ if hasattr(self.iterable, "close"):
663
+ self.iterable.close()
664
+
665
+
666
+ def _make_chunk_iter(stream, limit, buffer_size):
667
+ """Helper for the line and chunk iter functions."""
668
+ if isinstance(stream, (bytes, bytearray, text_type)):
669
+ raise TypeError(
670
+ "Passed a string or byte object instead of true iterator or stream."
671
+ )
672
+ if not hasattr(stream, "read"):
673
+ for item in stream:
674
+ if item:
675
+ yield item
676
+ return
677
+ if not isinstance(stream, LimitedStream) and limit is not None:
678
+ stream = LimitedStream(stream, limit)
679
+ _read = stream.read
680
+ while 1:
681
+ item = _read(buffer_size)
682
+ if not item:
683
+ break
684
+ yield item
685
+
686
+
687
+ def make_line_iter(stream, limit=None, buffer_size=10 * 1024, cap_at_buffer=False):
688
+ """Safely iterates line-based over an input stream. If the input stream
689
+ is not a :class:`LimitedStream` the `limit` parameter is mandatory.
690
+
691
+ This uses the stream's :meth:`~file.read` method internally as opposite
692
+ to the :meth:`~file.readline` method that is unsafe and can only be used
693
+ in violation of the WSGI specification. The same problem applies to the
694
+ `__iter__` function of the input stream which calls :meth:`~file.readline`
695
+ without arguments.
696
+
697
+ If you need line-by-line processing it's strongly recommended to iterate
698
+ over the input stream using this helper function.
699
+
700
+ .. versionchanged:: 0.8
701
+ This function now ensures that the limit was reached.
702
+
703
+ .. versionadded:: 0.9
704
+ added support for iterators as input stream.
705
+
706
+ .. versionadded:: 0.11.10
707
+ added support for the `cap_at_buffer` parameter.
708
+
709
+ :param stream: the stream or iterate to iterate over.
710
+ :param limit: the limit in bytes for the stream. (Usually
711
+ content length. Not necessary if the `stream`
712
+ is a :class:`LimitedStream`.
713
+ :param buffer_size: The optional buffer size.
714
+ :param cap_at_buffer: if this is set chunks are split if they are longer
715
+ than the buffer size. Internally this is implemented
716
+ that the buffer size might be exhausted by a factor
717
+ of two however.
718
+ """
719
+ _iter = _make_chunk_iter(stream, limit, buffer_size)
720
+
721
+ first_item = next(_iter, "")
722
+ if not first_item:
723
+ return
724
+
725
+ s = make_literal_wrapper(first_item)
726
+ empty = s("")
727
+ cr = s("\r")
728
+ lf = s("\n")
729
+ crlf = s("\r\n")
730
+
731
+ _iter = chain((first_item,), _iter)
732
+
733
+ def _iter_basic_lines():
734
+ _join = empty.join
735
+ buffer = []
736
+ while 1:
737
+ new_data = next(_iter, "")
738
+ if not new_data:
739
+ break
740
+ new_buf = []
741
+ buf_size = 0
742
+ for item in chain(buffer, new_data.splitlines(True)):
743
+ new_buf.append(item)
744
+ buf_size += len(item)
745
+ if item and item[-1:] in crlf:
746
+ yield _join(new_buf)
747
+ new_buf = []
748
+ elif cap_at_buffer and buf_size >= buffer_size:
749
+ rv = _join(new_buf)
750
+ while len(rv) >= buffer_size:
751
+ yield rv[:buffer_size]
752
+ rv = rv[buffer_size:]
753
+ new_buf = [rv]
754
+ buffer = new_buf
755
+ if buffer:
756
+ yield _join(buffer)
757
+
758
+ # This hackery is necessary to merge 'foo\r' and '\n' into one item
759
+ # of 'foo\r\n' if we were unlucky and we hit a chunk boundary.
760
+ previous = empty
761
+ for item in _iter_basic_lines():
762
+ if item == lf and previous[-1:] == cr:
763
+ previous += item
764
+ item = empty
765
+ if previous:
766
+ yield previous
767
+ previous = item
768
+ if previous:
769
+ yield previous
770
+
771
+
772
+ def make_chunk_iter(
773
+ stream, separator, limit=None, buffer_size=10 * 1024, cap_at_buffer=False
774
+ ):
775
+ """Works like :func:`make_line_iter` but accepts a separator
776
+ which divides chunks. If you want newline based processing
777
+ you should use :func:`make_line_iter` instead as it
778
+ supports arbitrary newline markers.
779
+
780
+ .. versionadded:: 0.8
781
+
782
+ .. versionadded:: 0.9
783
+ added support for iterators as input stream.
784
+
785
+ .. versionadded:: 0.11.10
786
+ added support for the `cap_at_buffer` parameter.
787
+
788
+ :param stream: the stream or iterate to iterate over.
789
+ :param separator: the separator that divides chunks.
790
+ :param limit: the limit in bytes for the stream. (Usually
791
+ content length. Not necessary if the `stream`
792
+ is otherwise already limited).
793
+ :param buffer_size: The optional buffer size.
794
+ :param cap_at_buffer: if this is set chunks are split if they are longer
795
+ than the buffer size. Internally this is implemented
796
+ that the buffer size might be exhausted by a factor
797
+ of two however.
798
+ """
799
+ _iter = _make_chunk_iter(stream, limit, buffer_size)
800
+
801
+ first_item = next(_iter, "")
802
+ if not first_item:
803
+ return
804
+
805
+ _iter = chain((first_item,), _iter)
806
+ if isinstance(first_item, text_type):
807
+ separator = to_unicode(separator)
808
+ _split = re.compile(r"(%s)" % re.escape(separator)).split
809
+ _join = u"".join
810
+ else:
811
+ separator = to_bytes(separator)
812
+ _split = re.compile(b"(" + re.escape(separator) + b")").split
813
+ _join = b"".join
814
+
815
+ buffer = []
816
+ while 1:
817
+ new_data = next(_iter, "")
818
+ if not new_data:
819
+ break
820
+ chunks = _split(new_data)
821
+ new_buf = []
822
+ buf_size = 0
823
+ for item in chain(buffer, chunks):
824
+ if item == separator:
825
+ yield _join(new_buf)
826
+ new_buf = []
827
+ buf_size = 0
828
+ else:
829
+ buf_size += len(item)
830
+ new_buf.append(item)
831
+
832
+ if cap_at_buffer and buf_size >= buffer_size:
833
+ rv = _join(new_buf)
834
+ while len(rv) >= buffer_size:
835
+ yield rv[:buffer_size]
836
+ rv = rv[buffer_size:]
837
+ new_buf = [rv]
838
+ buf_size = len(rv)
839
+
840
+ buffer = new_buf
841
+ if buffer:
842
+ yield _join(buffer)
843
+
844
+
845
+ @implements_iterator
846
+ class LimitedStream(io.IOBase):
847
+ """Wraps a stream so that it doesn't read more than n bytes. If the
848
+ stream is exhausted and the caller tries to get more bytes from it
849
+ :func:`on_exhausted` is called which by default returns an empty
850
+ string. The return value of that function is forwarded
851
+ to the reader function. So if it returns an empty string
852
+ :meth:`read` will return an empty string as well.
853
+
854
+ The limit however must never be higher than what the stream can
855
+ output. Otherwise :meth:`readlines` will try to read past the
856
+ limit.
857
+
858
+ .. admonition:: Note on WSGI compliance
859
+
860
+ calls to :meth:`readline` and :meth:`readlines` are not
861
+ WSGI compliant because it passes a size argument to the
862
+ readline methods. Unfortunately the WSGI PEP is not safely
863
+ implementable without a size argument to :meth:`readline`
864
+ because there is no EOF marker in the stream. As a result
865
+ of that the use of :meth:`readline` is discouraged.
866
+
867
+ For the same reason iterating over the :class:`LimitedStream`
868
+ is not portable. It internally calls :meth:`readline`.
869
+
870
+ We strongly suggest using :meth:`read` only or using the
871
+ :func:`make_line_iter` which safely iterates line-based
872
+ over a WSGI input stream.
873
+
874
+ :param stream: the stream to wrap.
875
+ :param limit: the limit for the stream, must not be longer than
876
+ what the string can provide if the stream does not
877
+ end with `EOF` (like `wsgi.input`)
878
+ """
879
+
880
+ def __init__(self, stream, limit):
881
+ self._read = stream.read
882
+ self._readline = stream.readline
883
+ self._pos = 0
884
+ self.limit = limit
885
+
886
+ def __iter__(self):
887
+ return self
888
+
889
+ @property
890
+ def is_exhausted(self):
891
+ """If the stream is exhausted this attribute is `True`."""
892
+ return self._pos >= self.limit
893
+
894
+ def on_exhausted(self):
895
+ """This is called when the stream tries to read past the limit.
896
+ The return value of this function is returned from the reading
897
+ function.
898
+ """
899
+ # Read null bytes from the stream so that we get the
900
+ # correct end of stream marker.
901
+ return self._read(0)
902
+
903
+ def on_disconnect(self):
904
+ """What should happen if a disconnect is detected? The return
905
+ value of this function is returned from read functions in case
906
+ the client went away. By default a
907
+ :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised.
908
+ """
909
+ from .exceptions import ClientDisconnected
910
+
911
+ raise ClientDisconnected()
912
+
913
+ def exhaust(self, chunk_size=1024 * 64):
914
+ """Exhaust the stream. This consumes all the data left until the
915
+ limit is reached.
916
+
917
+ :param chunk_size: the size for a chunk. It will read the chunk
918
+ until the stream is exhausted and throw away
919
+ the results.
920
+ """
921
+ to_read = self.limit - self._pos
922
+ chunk = chunk_size
923
+ while to_read > 0:
924
+ chunk = min(to_read, chunk)
925
+ self.read(chunk)
926
+ to_read -= chunk
927
+
928
+ def read(self, size=None):
929
+ """Read `size` bytes or if size is not provided everything is read.
930
+
931
+ :param size: the number of bytes read.
932
+ """
933
+ if self._pos >= self.limit:
934
+ return self.on_exhausted()
935
+ if size is None or size == -1: # -1 is for consistence with file
936
+ size = self.limit
937
+ to_read = min(self.limit - self._pos, size)
938
+ try:
939
+ read = self._read(to_read)
940
+ except (IOError, ValueError):
941
+ return self.on_disconnect()
942
+ if to_read and len(read) != to_read:
943
+ return self.on_disconnect()
944
+ self._pos += len(read)
945
+ return read
946
+
947
+ def readline(self, size=None):
948
+ """Reads one line from the stream."""
949
+ if self._pos >= self.limit:
950
+ return self.on_exhausted()
951
+ if size is None:
952
+ size = self.limit - self._pos
953
+ else:
954
+ size = min(size, self.limit - self._pos)
955
+ try:
956
+ line = self._readline(size)
957
+ except (ValueError, IOError):
958
+ return self.on_disconnect()
959
+ if size and not line:
960
+ return self.on_disconnect()
961
+ self._pos += len(line)
962
+ return line
963
+
964
+ def readlines(self, size=None):
965
+ """Reads a file into a list of strings. It calls :meth:`readline`
966
+ until the file is read to the end. It does support the optional
967
+ `size` argument if the underlying stream supports it for
968
+ `readline`.
969
+ """
970
+ last_pos = self._pos
971
+ result = []
972
+ if size is not None:
973
+ end = min(self.limit, last_pos + size)
974
+ else:
975
+ end = self.limit
976
+ while 1:
977
+ if size is not None:
978
+ size -= last_pos - self._pos
979
+ if self._pos >= end:
980
+ break
981
+ result.append(self.readline(size))
982
+ if size is not None:
983
+ last_pos = self._pos
984
+ return result
985
+
986
+ def tell(self):
987
+ """Returns the position of the stream.
988
+
989
+ .. versionadded:: 0.9
990
+ """
991
+ return self._pos
992
+
993
+ def __next__(self):
994
+ line = self.readline()
995
+ if not line:
996
+ raise StopIteration()
997
+ return line
998
+
999
+ def readable(self):
1000
+ return True