### Defining a backoff event handler (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Provides an example of a function (`backoff_hdlr`) that can be used as an event handler for backoff events (`on_success`, `on_backoff`, `on_giveup`). The handler receives a dictionary (`details`) containing information about the retry attempt, such as wait time, tries, target function, arguments, etc. Requires the `backoff` library. ```python def backoff_hdlr(details): print ("Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with args {args} and kwargs " "{kwargs}".format(**details)) @backoff.on_exception(backoff.expo, ``` -------------------------------- ### Using callable for runtime backoff configuration (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Illustrates how to provide decorator arguments, like `max_time`, as callables. This allows the value to be determined at runtime rather than import time, useful for accessing configuration settings that aren't available globally at import. The `lookup_max_time` function is called when a retry is needed. Requires the `backoff` library. ```python def lookup_max_time(): # pretend we have a global reference to 'app' here # and that it has a dictionary-like 'config' property return app.config["BACKOFF_MAX_TIME"] @backoff.on_exception(backoff.expo, ValueError, max_time=lookup_max_time) ``` -------------------------------- ### Using backoff.on_predicate with runtime generator for HTTP 429 (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Demonstrates using `backoff.on_predicate` with the `backoff.runtime` generator to handle HTTP 429 responses. The `predicate` checks for status code 429, and the `value` callable extracts the wait time from the `Retry-After` header. `jitter=None` is used. Requires `backoff` and `requests` libraries. ```python @backoff.on_predicate( backoff.runtime, predicate=lambda r: r.status_code == 429, value=lambda r: int(r.headers.get("Retry-After")), jitter=None, ) def get_url(): return requests.get(url) ``` -------------------------------- ### Using backoff.on_predicate with fibo and default predicate (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Shows a more concise version of using `backoff.on_predicate` with `backoff.fibo`. It retries if the decorated function's return value is falsey (the default predicate), using Fibonacci backoff up to `max_value=13`. Requires the `backoff` library. ```python @backoff.on_predicate(backoff.fibo, max_value=13) def poll_for_message(queue): return queue.get() ``` -------------------------------- ### Retrying with Maximum Attempts (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Demonstrates using the `max_tries` keyword argument with `@backoff.on_exception` to specify the maximum number of times the decorated function should be called (including the initial call) before giving up. ```python @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_tries=8, jitter=None) def get_url(url): return requests.get(url) ``` -------------------------------- ### Set Default Backoff Logger Level Source: https://github.com/litl/backoff/blob/master/README.rst Demonstrates setting the logging level for the default 'backoff' logger. Setting it to `logging.ERROR` will only log giveup events, while the default `logging.INFO` logs retry events. ```python logging.getLogger('backoff').setLevel(logging.ERROR) ``` -------------------------------- ### Combining multiple backoff decorators (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Shows how to apply multiple backoff decorators to a single function. It retries on falsey return value using Fibonacci backoff (`on_predicate`) and also retries on specific exceptions (`requests.exceptions.HTTPError`, `requests.exceptions.Timeout`) using exponential backoff (`on_exception`) with different maximum retry times. Requires `backoff` and `requests` libraries. ```python @backoff.on_predicate(backoff.fibo, max_value=13) @backoff.on_exception(backoff.expo, requests.exceptions.HTTPError, max_time=60) @backoff.on_exception(backoff.expo, requests.exceptions.Timeout, max_time=300) def poll_for_message(queue): return queue.get() ``` -------------------------------- ### Configure Default Backoff Logger Handler Source: https://github.com/litl/backoff/blob/master/README.rst Shows how to add a handler, such as a `StreamHandler`, to the default 'backoff' logger. This makes backoff and retry attempts visible in the console or other configured output. ```python logging.getLogger('backoff').addHandler(logging.StreamHandler()) ``` -------------------------------- ### Using backoff.on_predicate with fibo and empty list predicate (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Demonstrates using the `backoff.on_predicate` decorator with the `backoff.fibo` wait generator. It retries the decorated function `poll_for_messages` if its return value is an empty list (`[]`), using a Fibonacci sequence for wait times, capped by `max_value=13`. Requires the `backoff` library. ```python @backoff.on_predicate(backoff.fibo, lambda x: x == [], max_value=13) def poll_for_messages(queue): return queue.get() ``` -------------------------------- ### Using backoff.on_predicate with constant interval (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Illustrates using `backoff.on_predicate` with the `backoff.constant` wait generator. It retries if the decorated function's return value is falsey (default predicate), waiting a fixed `interval=1` second between retries. `jitter=None` disables random variation in wait times. Requires the `backoff` library. ```python @backoff.on_predicate(backoff.constant, jitter=None, interval=1) def poll_for_message(queue): return queue.get() ``` -------------------------------- ### Retrying with Maximum Total Time (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Illustrates using the `max_time` keyword argument with `@backoff.on_exception` to set a limit on the total cumulative time (in seconds) allowed for retries before giving up and potentially re-raising the exception. ```python @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_time=60) def get_url(url): return requests.get(url) ``` -------------------------------- ### Retrying on Multiple Exceptions (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Shows how to configure the `@backoff.on_exception` decorator to retry a function when any exception from a specified tuple of exception types (`requests.exceptions.Timeout`, `requests.exceptions.ConnectionError`) is raised. ```python @backoff.on_exception(backoff.expo, (requests.exceptions.Timeout, requests.exceptions.ConnectionError)) def get_url(url): return requests.get(url) ``` -------------------------------- ### Retry on Exception with Multiple Handlers (Synchronous) Source: https://github.com/litl/backoff/blob/master/README.rst Shows how to provide an iterable (like a list) of handler functions to the `on_backoff` argument of the `backoff.on_exception` decorator. All provided handlers will be called sequentially on each backoff event. ```python @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, on_backoff=[backoff_hdlr1, backoff_hdlr2]) def get_url(url): return requests.get(url) ``` -------------------------------- ### Retry on Exception (Asynchronous) Source: https://github.com/litl/backoff/blob/master/README.rst Illustrates using the `backoff.on_exception` decorator with an asynchronous function (coroutine) using `asyncio` and `aiohttp`. The decorator correctly handles retries for coroutines. ```python @backoff.on_exception(backoff.expo, aiohttp.ClientError, max_time=60) async def get_url(url): async with aiohttp.ClientSession(raise_for_status=True) as session: async with session.get(url) as response: return await response.text() ``` -------------------------------- ### Specify Logger Object in Decorator Source: https://github.com/litl/backoff/blob/master/README.rst Shows how to configure a custom logger object and then pass the logger object directly to the `logger` keyword argument in the `on_exception` decorator. ```python my_logger = logging.getLogger('my_logger') my_handler = logging.StreamHandler() my_logger.addHandler(my_handler) my_logger.setLevel(logging.ERROR) @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, logger=my_logger) # ... ``` -------------------------------- ### Retrying with Custom Give Up Condition (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Shows how to use the `giveup` keyword argument with `@backoff.on_exception` to provide a custom function that inspects the raised exception instance and returns `True` if the retry process should stop. ```python def fatal_code(e): return 400 <= e.response.status_code < 500 @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_time=300, giveup=fatal_code) def get_url(url): return requests.get(url) ``` -------------------------------- ### Retry on Exception with Single Handler (Synchronous) Source: https://github.com/litl/backoff/blob/master/README.rst Demonstrates applying the `backoff.on_exception` decorator to a synchronous function to automatically retry execution when a specified exception occurs. A single handler function is called on each backoff event. ```python @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, on_backoff=backoff_hdlr) def get_url(url): return requests.get(url) ``` -------------------------------- ### Retrying on Single Exception (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Demonstrates using the `@backoff.on_exception` decorator with exponential backoff (`backoff.expo`) to automatically retry a function (`get_url`) whenever a specific exception (`requests.exceptions.RequestException`) is raised during its execution. ```python @backoff.on_exception(backoff.expo, requests.exceptions.RequestException) def get_url(url): return requests.get(url) ``` -------------------------------- ### Specify Logger by Name in Decorator Source: https://github.com/litl/backoff/blob/master/README.rst Explains how to specify an alternate logger for backoff events by providing the logger's name as a string to the `logger` keyword argument in the `on_exception` decorator. ```python @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, logger='my_logger') # ... ``` -------------------------------- ### Retrying Without Raising on Give Up (Python) Source: https://github.com/litl/backoff/blob/master/README.rst Illustrates using `raise_on_giveup=False` alongside a `giveup` function with `@backoff.on_exception`. If the give up condition is met, the exception is suppressed, and the decorated function returns `None` instead of re-raising. ```python def fatal_code(e): return 400 <= e.response.status_code < 500 @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_time=300, raise_on_giveup=False, giveup=fatal_code) def get_url(url): return requests.get(url) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.