pyramid-retry 2.2__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.
@@ -0,0 +1,311 @@
1
+ import inspect
2
+ from pyramid.config import PHASE1_CONFIG
3
+ from pyramid.exceptions import ConfigurationError
4
+ from zope.interface import (
5
+ Attribute,
6
+ Interface,
7
+ alsoProvides,
8
+ classImplements,
9
+ implementer,
10
+ )
11
+
12
+
13
+ class IRetryableError(Interface):
14
+ """
15
+ A marker interface for retryable errors.
16
+
17
+ An interface can be applied to any ``Exception`` class or object to
18
+ indicate that it should be treated as a :term:`retryable error`.
19
+
20
+ """
21
+
22
+
23
+ class IBeforeRetry(Interface):
24
+ """
25
+ An event emitted immediately prior to throwing away the request
26
+ and creating a new one.
27
+
28
+ This event may be useful when state is stored on the ``request.environ``
29
+ that needs to be updated before a new request is created.
30
+
31
+ """
32
+
33
+ environ = Attribute('The environ object that is reused between requests.')
34
+ request = Attribute('The request object that is being discarded.')
35
+ exception = Attribute('The exception that request processing raised.')
36
+ response = Attribute(
37
+ 'The response object that is being discarded. '
38
+ 'This may be ``None`` if no response was generated, '
39
+ 'which happens when request processing raises an '
40
+ "exception that isn't caught by any exception view."
41
+ )
42
+
43
+
44
+ @implementer(IBeforeRetry)
45
+ class BeforeRetry(object):
46
+ """
47
+ An event emitted immediately prior to throwing away the request
48
+ and creating a new one.
49
+
50
+ This event may be useful when state is stored on the ``request.environ``
51
+ that needs to be updated before a new request is created.
52
+
53
+ :ivar request: The :class:`pyramid.request.Request` object that is being
54
+ discarded.
55
+
56
+ """
57
+
58
+ def __init__(self, request, exception, response=None):
59
+ self.request = request
60
+ self.environ = request.environ
61
+ self.exception = exception
62
+ self.response = response
63
+
64
+
65
+ @implementer(IRetryableError)
66
+ class RetryableException(Exception):
67
+ """A retryable exception should be raised when an error occurs."""
68
+
69
+
70
+ def RetryableExecutionPolicy(attempts=3, activate_hook=None):
71
+ """
72
+ Create a :term:`execution policy` that catches any
73
+ :term:`retryable error` and sends it through the pipeline again up to
74
+ a maximum of ``attempts`` attempts.
75
+
76
+ If ``activate_hook`` is set it will be consulted prior to each request
77
+ to determine if retries should be enabled. It should return a number > 0
78
+ of attempts to be used or ``None`` which will indicate to use the default
79
+ number of attempts.
80
+
81
+ """
82
+ assert attempts > 0
83
+
84
+ def retry_policy(environ, router):
85
+ # make the original request
86
+ request_ctx = router.request_context(environ)
87
+ request = request_ctx.begin()
88
+ try:
89
+ if activate_hook:
90
+ retry_attempts = activate_hook(request)
91
+ if retry_attempts is None:
92
+ retry_attempts = attempts
93
+ else:
94
+ assert retry_attempts > 0
95
+ else:
96
+ retry_attempts = attempts
97
+
98
+ # if we are supporting multiple attempts then we must make
99
+ # make the body seekable in order to re-use it across multiple
100
+ # attempts. make_body_seekable will copy wsgi.input if
101
+ # necessary, otherwise it will rewind the copy to position zero
102
+ if retry_attempts != 1:
103
+ request.make_body_seekable()
104
+
105
+ # Catch make_body_seekable (e.g. 408 RequestTimeout)
106
+ # and activate_hook exceptions and clean up.
107
+ except BaseException:
108
+ request_ctx.end()
109
+ raise
110
+
111
+ for number in range(retry_attempts):
112
+ # track the attempt info in the environ
113
+ # try to set it as soon as possible so that it's available
114
+ # in the request factory and elsewhere if people want it
115
+ # note: set all of these values here as they are cleared after
116
+ # each attempt
117
+ environ['retry.attempt'] = number
118
+ environ['retry.attempts'] = retry_attempts
119
+
120
+ # if we are not on the first attempt then we should start
121
+ # with a new request object and throw away any changes to
122
+ # the old object, however we do this carefully to try and
123
+ # avoid extra copies of the body
124
+ if number > 0:
125
+ # try to make sure this code stays in sync with pyramid's
126
+ # router which normally creates requests
127
+ request_ctx = router.request_context(environ)
128
+ request = request_ctx.begin()
129
+
130
+ try:
131
+ response = router.invoke_request(request)
132
+
133
+ # check for a squashed exception and handle it
134
+ # this would happen if an exception view was invoked and
135
+ # rendered an error response
136
+ exc = getattr(request, 'exception', None)
137
+ if exc is not None:
138
+ # if this is a retryable exception then continue to the
139
+ # next attempt, discarding the current response
140
+ if is_error_retryable(request, exc):
141
+ request.registry.notify(
142
+ BeforeRetry(request, exc, response=response)
143
+ )
144
+ continue
145
+
146
+ return response
147
+
148
+ except Exception as exc:
149
+ # if this was the last attempt or the exception is not
150
+ # retryable then there's nothing left for us to do
151
+ if not is_error_retryable(request, exc):
152
+ raise
153
+
154
+ else:
155
+ request.registry.notify(BeforeRetry(request, exc))
156
+
157
+ # cleanup any changes we made to the request
158
+ finally:
159
+ request_ctx.end()
160
+
161
+ del environ['retry.attempt']
162
+ del environ['retry.attempts']
163
+
164
+ return retry_policy
165
+
166
+
167
+ def mark_error_retryable(error):
168
+ """
169
+ Mark an exception instance or type as retryable. If this exception
170
+ is caught by ``pyramid_retry`` then it may retry the request.
171
+
172
+ """
173
+ if isinstance(error, Exception):
174
+ alsoProvides(error, IRetryableError)
175
+ elif inspect.isclass(error) and issubclass(error, Exception):
176
+ classImplements(error, IRetryableError)
177
+ else:
178
+ raise ValueError(
179
+ 'only exception objects or types may be marked retryable'
180
+ )
181
+
182
+
183
+ def is_error_retryable(request, exc):
184
+ """
185
+ Return ``True`` if the exception is recognized as :term:`retryable error`.
186
+
187
+ This will return ``False`` if the request is on its last attempt.
188
+ This will return ``False`` if ``pyramid_retry`` is inactive for the
189
+ request.
190
+
191
+ """
192
+ if is_last_attempt(request):
193
+ return False
194
+
195
+ return isinstance(exc, RetryableException) or IRetryableError.providedBy(
196
+ exc
197
+ )
198
+
199
+
200
+ def is_last_attempt(request):
201
+ """
202
+ Return ``True`` if the request is on its last attempt, meaning that
203
+ ``pyramid_retry`` will not be issuing any new attempts, regardless of
204
+ what happens when executing this request.
205
+
206
+ This will return ``True`` if ``pyramid_retry`` is inactive for the
207
+ request.
208
+
209
+ """
210
+ environ = request.environ
211
+ attempt = environ.get('retry.attempt')
212
+ attempts = environ.get('retry.attempts')
213
+ if attempt is None or attempts is None:
214
+ return True
215
+
216
+ return attempt + 1 == attempts
217
+
218
+
219
+ class RetryableErrorPredicate(object):
220
+ """
221
+ A :term:`view predicate` registered as ``retryable_error``. Can be
222
+ used to determine if an exception view should execute based on whether
223
+ the exception is a :term:`retryable error`.
224
+
225
+ .. seealso:: See :func:`pyramid_retry.is_error_retryable`.
226
+
227
+ """
228
+
229
+ def __init__(self, val, config):
230
+ if not isinstance(val, bool):
231
+ raise ConfigurationError(
232
+ 'The "retryable_error" view predicate value must be '
233
+ 'True or False.',
234
+ )
235
+ self.val = val
236
+
237
+ def text(self):
238
+ return 'retryable_error = %s' % (self.val,)
239
+
240
+ phash = text
241
+
242
+ def __call__(self, context, request):
243
+ exc = getattr(request, 'exception', None)
244
+ is_retryable = is_error_retryable(request, exc)
245
+ return (self.val and is_retryable) or (
246
+ not self.val and not is_retryable
247
+ )
248
+
249
+
250
+ class LastAttemptPredicate(object):
251
+ """
252
+ A :term:`view predicate` registered as ``last_retry_attempt``. Can be used
253
+ to determine if an exception view should execute based on whether it's
254
+ the last retry attempt before aborting the request.
255
+
256
+ .. seealso:: See :func:`pyramid_retry.is_last_attempt`.
257
+
258
+ """
259
+
260
+ def __init__(self, val, config):
261
+ if not isinstance(val, bool):
262
+ raise ConfigurationError(
263
+ 'The "last_retry_attempt" view predicate value must be '
264
+ 'True or False.',
265
+ )
266
+ self.val = val
267
+
268
+ def text(self):
269
+ return 'last_retry_attempt = %s' % (self.val,)
270
+
271
+ phash = text
272
+
273
+ def __call__(self, context, request):
274
+ is_last = is_last_attempt(request)
275
+ return (self.val and is_last) or (not self.val and not is_last)
276
+
277
+
278
+ def includeme(config):
279
+ """
280
+ Activate the ``pyramid_retry`` execution policy in your application.
281
+
282
+ This will add the :func:`pyramid_retry.RetryableErrorPolicy` with
283
+ ``attempts`` pulled from the ``retry.attempts`` setting.
284
+
285
+ The ``last_retry_attempt`` and ``retryable_error`` view predicates
286
+ are registered.
287
+
288
+ This should be included in your Pyramid application via
289
+ ``config.include('pyramid_retry')``.
290
+
291
+ """
292
+ settings = config.get_settings()
293
+
294
+ config.add_view_predicate('last_retry_attempt', LastAttemptPredicate)
295
+ config.add_view_predicate('retryable_error', RetryableErrorPredicate)
296
+
297
+ def register():
298
+ attempts = int(settings.get('retry.attempts') or 3)
299
+ settings['retry.attempts'] = attempts
300
+
301
+ activate_hook = settings.get('retry.activate_hook')
302
+ activate_hook = config.maybe_dotted(activate_hook)
303
+
304
+ policy = RetryableExecutionPolicy(
305
+ attempts,
306
+ activate_hook=activate_hook,
307
+ )
308
+ config.set_execution_policy(policy)
309
+
310
+ # defer registration to allow time to modify settings
311
+ config.action(None, register, order=PHASE1_CONFIG)
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyramid_retry
3
+ Version: 2.2
4
+ Summary: An execution policy for Pyramid that supports retrying requests after certain failure exceptions.
5
+ Author-email: Michael Merickel <pylons-discuss@googlegroups.com>
6
+ License-Expression: MIT
7
+ Project-URL: Changelog, https://docs.pylonsproject.org/projects/pyramid_retry/en/latest/changes.html
8
+ Project-URL: Documentation, https://docs.pylonsproject.org/projects/pyramid_retry/en/latest/index.html
9
+ Project-URL: Homepage, https://github.com/Pylons/pyramid_retry
10
+ Project-URL: Issue Tracker, https://github.com/Pylons/pyramid_retry/issues
11
+ Keywords: attempt,pyramid,retry,wsgi
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Framework :: Pyramid
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: English
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/x-rst
27
+ License-File: LICENSE.txt
28
+ Requires-Dist: pyramid>=1.9
29
+ Requires-Dist: zope.interface
30
+ Dynamic: license-file
31
+
32
+ =============
33
+ pyramid_retry
34
+ =============
35
+
36
+ .. image:: https://img.shields.io/pypi/v/pyramid_retry.svg
37
+ :target: https://pypi.python.org/pypi/pyramid_retry
38
+
39
+ .. image:: https://github.com/Pylons/pyramid_retry/actions/workflows/ci-tests.yml/badge.svg?branch=main
40
+ :target: https://github.com/Pylons/pyramid_retry/actions/workflows/ci-tests.yml?query=branch%3Amain
41
+
42
+ .. image:: https://readthedocs.org/projects/pyramid_retry/badge/?version=latest
43
+ :target: https://readthedocs.org/projects/pyramid_retry/?badge=latest
44
+ :alt: Documentation Status
45
+
46
+ ``pyramid_retry`` is an execution policy for Pyramid that wraps requests and
47
+ can retry them a configurable number of times under certain "retryable" error
48
+ conditions before indicating a failure to the client.
49
+
50
+ See https://docs.pylonsproject.org/projects/pyramid_retry/en/latest/
51
+ or ``docs/index.rst`` in this distribution for detailed
52
+ documentation.
53
+
54
+ 2.2 (2026-11-23)
55
+ ================
56
+
57
+ - Drop support for Python 2.7 and 3.4 through 3.10.
58
+
59
+ - Add support for Python 3.11, 3.12, 3.13, 3.14, and 3.15.
60
+
61
+ - Stop using the deprecated ``pkg_resources`` api in the docs.
62
+
63
+ - Switch packaging metadata from ``setup.py`` to ``pyproject.toml`` and use
64
+ an SPDX license expression. The ``testing`` and ``docs`` extras are replaced
65
+ by dependency groups.
66
+
67
+ 2.1.1 (2020-03-21)
68
+ ==================
69
+
70
+ - Ensure the threadlocals are properly popped if the ``activate_hook`` throws
71
+ an error or the request body fails to read due to a client disconnect.
72
+ See https://github.com/Pylons/pyramid_retry/pull/20
73
+
74
+ 2.1 (2019-09-30)
75
+ ================
76
+
77
+ - Add ``exception`` and ``response`` attributes to the
78
+ ``pyramid_retry.IBeforeRetry`` event.
79
+ See https://github.com/Pylons/pyramid_retry/pull/19
80
+
81
+ 2.0 (2019-06-06)
82
+ ================
83
+
84
+ - No longer call ``invoke_exception_view`` if the policy catches an exception.
85
+ If on the last attempt or non-retryable then the exception will now bubble
86
+ out of the app and into WSGI middleware.
87
+ See https://github.com/Pylons/pyramid_retry/pull/17
88
+
89
+ 1.0 (2018-10-18)
90
+ ================
91
+
92
+ - Support Python 3.7.
93
+
94
+ - Update the version we require for Pyramid to a non-prerelease so that pip and
95
+ other tools don't accidentally install pre-release software.
96
+ See https://github.com/Pylons/pyramid_retry/pull/13
97
+
98
+ 0.5 (2017-06-19)
99
+ ================
100
+
101
+ - Update the policy to to track changes in Pyramid 1.9b1. This is an
102
+ incompatible change and requires at least Pyramid 1.9b1.
103
+ See https://github.com/Pylons/pyramid_retry/pull/11
104
+
105
+ 0.4 (2017-06-12)
106
+ ================
107
+
108
+ - Add the ``mark_error_retryable`` function in order to easily mark
109
+ certain errors as retryable for ``pyramid_retry`` to detect.
110
+ See https://github.com/Pylons/pyramid_retry/pull/8
111
+
112
+ - Add the ``IBeforeRetry`` event that can be subscribed to be notified
113
+ when a retry is about to occur in order to perform cleanup on the
114
+ ``environ``. See https://github.com/Pylons/pyramid_retry/pull/9
115
+
116
+ 0.3 (2017-04-10)
117
+ ================
118
+
119
+ - Support a ``retry.activate_hook`` setting which can return a per-request
120
+ number of retries. See https://github.com/Pylons/pyramid_retry/pull/4
121
+
122
+ - Configuration is deferred so that settings may be changed after
123
+ ``config.include('pyramid_retry')`` is invoked until the configurator
124
+ is committed. See https://github.com/Pylons/pyramid_retry/pull/4
125
+
126
+ - Rename the view predicates to ``last_retry_attempt`` and
127
+ ``retryable_error``. See https://github.com/Pylons/pyramid_retry/pull/3
128
+
129
+ - Rename ``pyramid_retry.is_exc_retryable`` to
130
+ ``pyramid_retry.is_error_retryable``.
131
+ See https://github.com/Pylons/pyramid_retry/pull/3
132
+
133
+ 0.2 (2017-03-02)
134
+ ================
135
+
136
+ - Change the default attempts to 3 instead of 1.
137
+
138
+ - Rename the view predicates to ``is_last_attempt`` and ``is_exc_retryable``.
139
+
140
+ - Drop support for the ``tm.attempts`` setting.
141
+
142
+ - The ``retry.attempts`` setting is always set now in
143
+ ``registry.settings['retry.attempts']`` so that apps can inspect it.
144
+
145
+ 0.1 (2017-03-01)
146
+ ================
147
+
148
+ - Initial release.
@@ -0,0 +1,6 @@
1
+ pyramid_retry/__init__.py,sha256=UatG49OIwhPhg4csVaeg5mQavxAlCmpFtveO8UUDCv8,10278
2
+ pyramid_retry-2.2.dist-info/licenses/LICENSE.txt,sha256=A00PRhqlNz4ZwoTP4d_HKsO2MIHJ5YrGnaQBoVWjvRE,1065
3
+ pyramid_retry-2.2.dist-info/METADATA,sha256=p3zewKQH6cx1hxsqFWl8YHVJoa0xrypRnOcbjnGYJNE,5431
4
+ pyramid_retry-2.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ pyramid_retry-2.2.dist-info/top_level.txt,sha256=4l99L7ZFph71MA60Nh53dLrlkhXMhblvjBX83SGA4YY,14
6
+ pyramid_retry-2.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2017-2018 Michael Merickel
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pyramid_retry