| 1 |
Metadata-Version: 2.1 |
| 2 |
Name: backoff |
| 3 |
Version: 2.2.1 |
| 4 |
Summary: Function decoration for backoff and retry |
| 5 |
Home-page: https://github.com/litl/backoff |
| 6 |
License: MIT |
| 7 |
Keywords: retry,backoff,decorators |
| 8 |
Author: Bob Green |
| 9 |
Author-email: [email protected] |
| 10 |
Requires-Python: >=3.7,<4.0 |
| 11 |
Classifier: Development Status :: 5 - Production/Stable |
| 12 |
Classifier: Intended Audience :: Developers |
| 13 |
Classifier: License :: OSI Approved :: MIT License |
| 14 |
Classifier: Natural Language :: English |
| 15 |
Classifier: Operating System :: OS Independent |
| 16 |
Classifier: Programming Language :: Python |
| 17 |
Classifier: Programming Language :: Python :: 3 |
| 18 |
Classifier: Programming Language :: Python :: 3.7 |
| 19 |
Classifier: Programming Language :: Python :: 3.8 |
| 20 |
Classifier: Programming Language :: Python :: 3.9 |
| 21 |
Classifier: Programming Language :: Python :: 3.10 |
| 22 |
Classifier: Programming Language :: Python :: 3 |
| 23 |
Classifier: Programming Language :: Python :: 3.10 |
| 24 |
Classifier: Programming Language :: Python :: 3.7 |
| 25 |
Classifier: Programming Language :: Python :: 3.8 |
| 26 |
Classifier: Programming Language :: Python :: 3.9 |
| 27 |
Classifier: Topic :: Internet :: WWW/HTTP |
| 28 |
Classifier: Topic :: Software Development :: Libraries :: Python Modules |
| 29 |
Classifier: Topic :: Utilities |
| 30 |
Project-URL: Repository, https://github.com/litl/backoff |
| 31 |
Description-Content-Type: text/x-rst |
| 32 |
|
| 33 |
backoff |
| 34 |
======= |
| 35 |
|
| 36 |
.. image:: https://travis-ci.org/litl/backoff.svg |
| 37 |
:target: https://travis-ci.org/litl/backoff |
| 38 |
.. image:: https://coveralls.io/repos/litl/backoff/badge.svg |
| 39 |
:target: https://coveralls.io/r/litl/backoff?branch=python-3 |
| 40 |
.. image:: https://github.com/litl/backoff/workflows/CodeQL/badge.svg |
| 41 |
:target: https://github.com/litl/backoff/actions/workflows/codeql-analysis.yml |
| 42 |
.. image:: https://img.shields.io/pypi/v/backoff.svg |
| 43 |
:target: https://pypi.python.org/pypi/backoff |
| 44 |
.. image:: https://img.shields.io/github/license/litl/backoff |
| 45 |
:target: https://github.com/litl/backoff/blob/master/LICENSE |
| 46 |
|
| 47 |
**Function decoration for backoff and retry** |
| 48 |
|
| 49 |
This module provides function decorators which can be used to wrap a |
| 50 |
function such that it will be retried until some condition is met. It |
| 51 |
is meant to be of use when accessing unreliable resources with the |
| 52 |
potential for intermittent failures i.e. network resources and external |
| 53 |
APIs. Somewhat more generally, it may also be of use for dynamically |
| 54 |
polling resources for externally generated content. |
| 55 |
|
| 56 |
Decorators support both regular functions for synchronous code and |
| 57 |
`asyncio <https://docs.python.org/3/library/asyncio.html>`__'s coroutines |
| 58 |
for asynchronous code. |
| 59 |
|
| 60 |
Examples |
| 61 |
======== |
| 62 |
|
| 63 |
Since Kenneth Reitz's `requests <http://python-requests.org>`_ module |
| 64 |
has become a defacto standard for synchronous HTTP clients in Python, |
| 65 |
networking examples below are written using it, but it is in no way required |
| 66 |
by the backoff module. |
| 67 |
|
| 68 |
@backoff.on_exception |
| 69 |
--------------------- |
| 70 |
|
| 71 |
The ``on_exception`` decorator is used to retry when a specified exception |
| 72 |
is raised. Here's an example using exponential backoff when any |
| 73 |
``requests`` exception is raised: |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
@backoff.on_exception(backoff.expo, |
| 78 |
requests.exceptions.RequestException) |
| 79 |
def get_url(url): |
| 80 |
return requests.get(url) |
| 81 |
|
| 82 |
The decorator will also accept a tuple of exceptions for cases where |
| 83 |
the same backoff behavior is desired for more than one exception type: |
| 84 |
|
| 85 |
.. code-block:: python |
| 86 |
|
| 87 |
@backoff.on_exception(backoff.expo, |
| 88 |
(requests.exceptions.Timeout, |
| 89 |
requests.exceptions.ConnectionError)) |
| 90 |
def get_url(url): |
| 91 |
return requests.get(url) |
| 92 |
|
| 93 |
**Give Up Conditions** |
| 94 |
|
| 95 |
Optional keyword arguments can specify conditions under which to give |
| 96 |
up. |
| 97 |
|
| 98 |
The keyword argument ``max_time`` specifies the maximum amount |
| 99 |
of total time in seconds that can elapse before giving up. |
| 100 |
|
| 101 |
.. code-block:: python |
| 102 |
|
| 103 |
@backoff.on_exception(backoff.expo, |
| 104 |
requests.exceptions.RequestException, |
| 105 |
max_time=60) |
| 106 |
def get_url(url): |
| 107 |
return requests.get(url) |
| 108 |
|
| 109 |
|
| 110 |
Keyword argument ``max_tries`` specifies the maximum number of calls |
| 111 |
to make to the target function before giving up. |
| 112 |
|
| 113 |
.. code-block:: python |
| 114 |
|
| 115 |
@backoff.on_exception(backoff.expo, |
| 116 |
requests.exceptions.RequestException, |
| 117 |
max_tries=8, |
| 118 |
jitter=None) |
| 119 |
def get_url(url): |
| 120 |
return requests.get(url) |
| 121 |
|
| 122 |
|
| 123 |
In some cases the raised exception instance itself may need to be |
| 124 |
inspected in order to determine if it is a retryable condition. The |
| 125 |
``giveup`` keyword arg can be used to specify a function which accepts |
| 126 |
the exception and returns a truthy value if the exception should not |
| 127 |
be retried: |
| 128 |
|
| 129 |
.. code-block:: python |
| 130 |
|
| 131 |
def fatal_code(e): |
| 132 |
return 400 <= e.response.status_code < 500 |
| 133 |
|
| 134 |
@backoff.on_exception(backoff.expo, |
| 135 |
requests.exceptions.RequestException, |
| 136 |
max_time=300, |
| 137 |
giveup=fatal_code) |
| 138 |
def get_url(url): |
| 139 |
return requests.get(url) |
| 140 |
|
| 141 |
By default, when a give up event occurs, the exception in question is reraised |
| 142 |
and so code calling an `on_exception`-decorated function may still |
| 143 |
need to do exception handling. This behavior can optionally be disabled |
| 144 |
using the `raise_on_giveup` keyword argument. |
| 145 |
|
| 146 |
In the code below, `requests.exceptions.RequestException` will not be raised |
| 147 |
when giveup occurs. Note that the decorated function will return `None` in this |
| 148 |
case, regardless of the logic in the `on_exception` handler. |
| 149 |
|
| 150 |
.. code-block:: python |
| 151 |
|
| 152 |
def fatal_code(e): |
| 153 |
return 400 <= e.response.status_code < 500 |
| 154 |
|
| 155 |
@backoff.on_exception(backoff.expo, |
| 156 |
requests.exceptions.RequestException, |
| 157 |
max_time=300, |
| 158 |
raise_on_giveup=False, |
| 159 |
giveup=fatal_code) |
| 160 |
def get_url(url): |
| 161 |
return requests.get(url) |
| 162 |
|
| 163 |
This is useful for non-mission critical code where you still wish to retry |
| 164 |
the code inside of `backoff.on_exception` but wish to proceed with execution |
| 165 |
even if all retries fail. |
| 166 |
|
| 167 |
@backoff.on_predicate |
| 168 |
--------------------- |
| 169 |
|
| 170 |
The ``on_predicate`` decorator is used to retry when a particular |
| 171 |
condition is true of the return value of the target function. This may |
| 172 |
be useful when polling a resource for externally generated content. |
| 173 |
|
| 174 |
Here's an example which uses a fibonacci sequence backoff when the |
| 175 |
return value of the target function is the empty list: |
| 176 |
|
| 177 |
.. code-block:: python |
| 178 |
|
| 179 |
@backoff.on_predicate(backoff.fibo, lambda x: x == [], max_value=13) |
| 180 |
def poll_for_messages(queue): |
| 181 |
return queue.get() |
| 182 |
|
| 183 |
Extra keyword arguments are passed when initializing the |
| 184 |
wait generator, so the ``max_value`` param above is passed as a keyword |
| 185 |
arg when initializing the fibo generator. |
| 186 |
|
| 187 |
When not specified, the predicate param defaults to the falsey test, |
| 188 |
so the above can more concisely be written: |
| 189 |
|
| 190 |
.. code-block:: python |
| 191 |
|
| 192 |
@backoff.on_predicate(backoff.fibo, max_value=13) |
| 193 |
def poll_for_message(queue): |
| 194 |
return queue.get() |
| 195 |
|
| 196 |
More simply, a function which continues polling every second until it |
| 197 |
gets a non-falsey result could be defined like like this: |
| 198 |
|
| 199 |
.. code-block:: python |
| 200 |
|
| 201 |
@backoff.on_predicate(backoff.constant, jitter=None, interval=1) |
| 202 |
def poll_for_message(queue): |
| 203 |
return queue.get() |
| 204 |
|
| 205 |
The jitter is disabled in order to keep the polling frequency fixed. |
| 206 |
|
| 207 |
@backoff.runtime |
| 208 |
---------------- |
| 209 |
|
| 210 |
You can also use the ``backoff.runtime`` generator to make use of the |
| 211 |
return value or thrown exception of the decorated method. |
| 212 |
|
| 213 |
For example, to use the value in the ``Retry-After`` header of the response: |
| 214 |
|
| 215 |
.. code-block:: python |
| 216 |
|
| 217 |
@backoff.on_predicate( |
| 218 |
backoff.runtime, |
| 219 |
predicate=lambda r: r.status_code == 429, |
| 220 |
value=lambda r: int(r.headers.get("Retry-After")), |
| 221 |
jitter=None, |
| 222 |
) |
| 223 |
def get_url(): |
| 224 |
return requests.get(url) |
| 225 |
|
| 226 |
Jitter |
| 227 |
------ |
| 228 |
|
| 229 |
A jitter algorithm can be supplied with the ``jitter`` keyword arg to |
| 230 |
either of the backoff decorators. This argument should be a function |
| 231 |
accepting the original unadulterated backoff value and returning it's |
| 232 |
jittered counterpart. |
| 233 |
|
| 234 |
As of version 1.2, the default jitter function ``backoff.full_jitter`` |
| 235 |
implements the 'Full Jitter' algorithm as defined in the AWS |
| 236 |
Architecture Blog's `Exponential Backoff And Jitter |
| 237 |
<https://www.awsarchitectureblog.com/2015/03/backoff.html>`_ post. |
| 238 |
Note that with this algorithm, the time yielded by the wait generator |
| 239 |
is actually the *maximum* amount of time to wait. |
| 240 |
|
| 241 |
Previous versions of backoff defaulted to adding some random number of |
| 242 |
milliseconds (up to 1s) to the raw sleep value. If desired, this |
| 243 |
behavior is now available as ``backoff.random_jitter``. |
| 244 |
|
| 245 |
Using multiple decorators |
| 246 |
------------------------- |
| 247 |
|
| 248 |
The backoff decorators may also be combined to specify different |
| 249 |
backoff behavior for different cases: |
| 250 |
|
| 251 |
.. code-block:: python |
| 252 |
|
| 253 |
@backoff.on_predicate(backoff.fibo, max_value=13) |
| 254 |
@backoff.on_exception(backoff.expo, |
| 255 |
requests.exceptions.HTTPError, |
| 256 |
max_time=60) |
| 257 |
@backoff.on_exception(backoff.expo, |
| 258 |
requests.exceptions.Timeout, |
| 259 |
max_time=300) |
| 260 |
def poll_for_message(queue): |
| 261 |
return queue.get() |
| 262 |
|
| 263 |
|
| 264 |
Runtime Configuration |
| 265 |
--------------------- |
| 266 |
|
| 267 |
The decorator functions ``on_exception`` and ``on_predicate`` are |
| 268 |
generally evaluated at import time. This is fine when the keyword args |
| 269 |
are passed as constant values, but suppose we want to consult a |
| 270 |
dictionary with configuration options that only become available at |
| 271 |
runtime. The relevant values are not available at import time. Instead, |
| 272 |
decorator functions can be passed callables which are evaluated at |
| 273 |
runtime to obtain the value: |
| 274 |
|
| 275 |
.. code-block:: python |
| 276 |
|
| 277 |
def lookup_max_time(): |
| 278 |
# pretend we have a global reference to 'app' here |
| 279 |
# and that it has a dictionary-like 'config' property |
| 280 |
return app.config["BACKOFF_MAX_TIME"] |
| 281 |
|
| 282 |
@backoff.on_exception(backoff.expo, |
| 283 |
ValueError, |
| 284 |
max_time=lookup_max_time) |
| 285 |
|
| 286 |
Event handlers |
| 287 |
-------------- |
| 288 |
|
| 289 |
Both backoff decorators optionally accept event handler functions |
| 290 |
using the keyword arguments ``on_success``, ``on_backoff``, and ``on_giveup``. |
| 291 |
This may be useful in reporting statistics or performing other custom |
| 292 |
logging. |
| 293 |
|
| 294 |
Handlers must be callables with a unary signature accepting a dict |
| 295 |
argument. This dict contains the details of the invocation. Valid keys |
| 296 |
include: |
| 297 |
|
| 298 |
* *target*: reference to the function or method being invoked |
| 299 |
* *args*: positional arguments to func |
| 300 |
* *kwargs*: keyword arguments to func |
| 301 |
* *tries*: number of invocation tries so far |
| 302 |
* *elapsed*: elapsed time in seconds so far |
| 303 |
* *wait*: seconds to wait (``on_backoff`` handler only) |
| 304 |
* *value*: value triggering backoff (``on_predicate`` decorator only) |
| 305 |
|
| 306 |
A handler which prints the details of the backoff event could be |
| 307 |
implemented like so: |
| 308 |
|
| 309 |
.. code-block:: python |
| 310 |
|
| 311 |
def backoff_hdlr(details): |
| 312 |
print ("Backing off {wait:0.1f} seconds after {tries} tries " |
| 313 |
"calling function {target} with args {args} and kwargs " |
| 314 |
"{kwargs}".format(**details)) |
| 315 |
|
| 316 |
@backoff.on_exception(backoff.expo, |
| 317 |
requests.exceptions.RequestException, |
| 318 |
on_backoff=backoff_hdlr) |
| 319 |
def get_url(url): |
| 320 |
return requests.get(url) |
| 321 |
|
| 322 |
**Multiple handlers per event type** |
| 323 |
|
| 324 |
In all cases, iterables of handler functions are also accepted, which |
| 325 |
are called in turn. For example, you might provide a simple list of |
| 326 |
handler functions as the value of the ``on_backoff`` keyword arg: |
| 327 |
|
| 328 |
.. code-block:: python |
| 329 |
|
| 330 |
@backoff.on_exception(backoff.expo, |
| 331 |
requests.exceptions.RequestException, |
| 332 |
on_backoff=[backoff_hdlr1, backoff_hdlr2]) |
| 333 |
def get_url(url): |
| 334 |
return requests.get(url) |
| 335 |
|
| 336 |
**Getting exception info** |
| 337 |
|
| 338 |
In the case of the ``on_exception`` decorator, all ``on_backoff`` and |
| 339 |
``on_giveup`` handlers are called from within the except block for the |
| 340 |
exception being handled. Therefore exception info is available to the |
| 341 |
handler functions via the python standard library, specifically |
| 342 |
``sys.exc_info()`` or the ``traceback`` module. The exception is also |
| 343 |
available at the *exception* key in the `details` dict passed to the |
| 344 |
handlers. |
| 345 |
|
| 346 |
Asynchronous code |
| 347 |
----------------- |
| 348 |
|
| 349 |
Backoff supports asynchronous execution in Python 3.5 and above. |
| 350 |
|
| 351 |
To use backoff in asynchronous code based on |
| 352 |
`asyncio <https://docs.python.org/3/library/asyncio.html>`__ |
| 353 |
you simply need to apply ``backoff.on_exception`` or ``backoff.on_predicate`` |
| 354 |
to coroutines. |
| 355 |
You can also use coroutines for the ``on_success``, ``on_backoff``, and |
| 356 |
``on_giveup`` event handlers, with the interface otherwise being identical. |
| 357 |
|
| 358 |
The following examples use `aiohttp <https://aiohttp.readthedocs.io/>`__ |
| 359 |
asynchronous HTTP client/server library. |
| 360 |
|
| 361 |
.. code-block:: python |
| 362 |
|
| 363 |
@backoff.on_exception(backoff.expo, aiohttp.ClientError, max_time=60) |
| 364 |
async def get_url(url): |
| 365 |
async with aiohttp.ClientSession(raise_for_status=True) as session: |
| 366 |
async with session.get(url) as response: |
| 367 |
return await response.text() |
| 368 |
|
| 369 |
Logging configuration |
| 370 |
--------------------- |
| 371 |
|
| 372 |
By default, backoff and retry attempts are logged to the 'backoff' |
| 373 |
logger. By default, this logger is configured with a NullHandler, so |
| 374 |
there will be nothing output unless you configure a handler. |
| 375 |
Programmatically, this might be accomplished with something as simple |
| 376 |
as: |
| 377 |
|
| 378 |
.. code-block:: python |
| 379 |
|
| 380 |
logging.getLogger('backoff').addHandler(logging.StreamHandler()) |
| 381 |
|
| 382 |
The default logging level is INFO, which corresponds to logging |
| 383 |
anytime a retry event occurs. If you would instead like to log |
| 384 |
only when a giveup event occurs, set the logger level to ERROR. |
| 385 |
|
| 386 |
.. code-block:: python |
| 387 |
|
| 388 |
logging.getLogger('backoff').setLevel(logging.ERROR) |
| 389 |
|
| 390 |
It is also possible to specify an alternate logger with the ``logger`` |
| 391 |
keyword argument. If a string value is specified the logger will be |
| 392 |
looked up by name. |
| 393 |
|
| 394 |
.. code-block:: python |
| 395 |
|
| 396 |
@backoff.on_exception(backoff.expo, |
| 397 |
requests.exceptions.RequestException, |
| 398 |
logger='my_logger') |
| 399 |
# ... |
| 400 |
|
| 401 |
It is also supported to specify a Logger (or LoggerAdapter) object |
| 402 |
directly. |
| 403 |
|
| 404 |
.. code-block:: python |
| 405 |
|
| 406 |
my_logger = logging.getLogger('my_logger') |
| 407 |
my_handler = logging.StreamHandler() |
| 408 |
my_logger.addHandler(my_handler) |
| 409 |
my_logger.setLevel(logging.ERROR) |
| 410 |
|
| 411 |
@backoff.on_exception(backoff.expo, |
| 412 |
requests.exceptions.RequestException, |
| 413 |
logger=my_logger) |
| 414 |
# ... |
| 415 |
|
| 416 |
Default logging can be disabled all together by specifying |
| 417 |
``logger=None``. In this case, if desired alternative logging behavior |
| 418 |
could be defined by using custom event handlers. |
| 419 |
|