Versatile async-friendly library to retry failed operations with configurable backoff strategies

Overview

riprova Build Status PyPI Coverage Status Documentation Status Quality Versions

riprova (meaning retry in Italian) is a small, general-purpose and versatile Python library that provides retry mechanisms with multiple backoff strategies for any sort of failed operations.

It's domain agnostic, highly customizable, extensible and provides a minimal API that's easy to instrument in any code base via decorators, context managers or raw API consumption.

For a brief introduction about backoff mechanisms for potential failed operations, read this article.

Features

  • Retry decorator for simple and idiomatic consumption.
  • Simple Pythonic programmatic interface.
  • Maximum retry timeout support.
  • Supports error whitelisting and blacklisting.
  • Supports custom error evaluation retry logic (useful to retry only in specific cases).
  • Automatically retry operations on raised exceptions.
  • Supports asynchronous coroutines with both async/await and yield from syntax.
  • Configurable maximum number of retry attempts.
  • Highly configurable supporting max retries, timeouts or retry notifier callback.
  • Built-in backoff strategies: constant, fibonacci and exponential backoffs.
  • Supports sync/async context managers.
  • Pluggable custom backoff strategies.
  • Lightweight library with almost zero embedding cost.
  • Works with Python +2.6, 3.0+ and PyPy.

Backoff strategies

List of built-in backoff strategies.

You can also implement your own one easily. See ConstantBackoff for an implementation reference.

Installation

Using pip package manager (requires pip 1.9+. Upgrade it running: pip install -U pip):

pip install -U riprova

Or install the latest sources from Github:

pip install -e git+git://github.com/h2non/riprova.git#egg=riprova

API

Examples

You can see more featured examples from the documentation site.

Basic usage examples:

import riprova

@riprova.retry
def task():
    """Retry operation if it fails with constant backoff (default)"""

@riprova.retry(backoff=riprova.ConstantBackoff(retries=5))
def task():
    """Retry operation if it fails with custom max number of retry attempts"""

@riprova.retry(backoff=riprova.ExponentialBackOff(factor=0.5))
def task():
    """Retry operation if it fails using exponential backoff"""

@riprova.retry(timeout=10)
def task():
    """Raises a TimeoutError if the retry loop exceeds from 10 seconds"""

def on_retry(err, next_try):
    print('Operation error: {}'.format(err))
    print('Next try in: {}ms'.format(next_try))

@riprova.retry(on_retry=on_retry)
def task():
    """Subscribe via function callback to every retry attempt"""

def evaluator(response):
    # Force retry operation if not a valid response
    if response.status >= 400:
        raise RuntimeError('invalid response status')  # or simple return True
    # Otherwise return False, meaning no retry
    return False

@riprova.retry(evaluator=evaluator)
def task():
    """Use a custom evaluator function to determine if the operation failed or not"""

@riprova.retry
async def task():
    """Asynchronous coroutines are also supported :)"""

Retry failed HTTP requests:

import pook
import requests
from riprova import retry

# Define HTTP mocks to simulate failed requests
pook.get('server.com').times(3).reply(503)
pook.get('server.com').times(1).reply(200).json({'hello': 'world'})


# Retry evaluator function used to determine if the operated failed or not
def evaluator(response):
    if response != 200:
        return Exception('failed request')  # you can also simply return True
    return False


# On retry even subscriptor
def on_retry(err, next_try):
    print('Operation error {}'.format(err))
    print('Next try in {}ms'.format(next_try))


# Register retriable operation
@retry(evaluator=evaluator, on_retry=on_retry)
def fetch(url):
    return requests.get(url)


# Run task that might fail
fetch('http://server.com')

License

MIT - Tomas Aparicio

Owner
Tom
Computers harasser
Tom
Turns any script into a telegram bot

pytobot Turns any script into a telegram bot Install pip install --upgrade pytobot Usage Script: while True: message = input() if message == "

Dmitry Kotov 17 Jan 06, 2023
WikiChecker - Repositorio oficial del complemento WikiChecker para NVDA.

WikiChecker Buscador rápido de artículos en Wikipedia. Introducción. El complemento WikiChecker para NVDA permite a los usuarios consultar de forma rá

2 Jan 10, 2022
Popcorn-time-api - Python API for interacting with the Popcorn Time Servers

Popcorn Time API 📝 CONTRIBUTIONS Before doing any contribution read CONTRIBUTIN

Antonio 3 Oct 31, 2022
Tiktok 2 Instagram With Python

Tiktok2Instagram 📸 About The Project What it does: Download the source video from a user inputted Tiktok URL. 📙 Add audio to the Tiktok video from a

Carter Belisle 4 Feb 06, 2022
As Slack no longer provides an API to invite people, this is a Selenium Python script to do so

As Slack no longer provides an API to invite people, this is a Selenium Python script to do so

discord vc exploit to lightly lag vcs

discord-vc-reconnector discord vc exploit to lag vcs how to use open the py file, then open devtools on discord, go to network and join a vc, dont sta

Tesco 30 Aug 09, 2022
A discord bot that manages your server's hedge fund

Can't Hide Money Bot A discord bot that manages your server's hedge fund Installing Install wkhtmltopdf sudo apt-get install wkhtmltopdf OR brew insta

Kelvin Abrokwa-Johnson 0 Oct 16, 2021
Gorrabot is a bot made to automate checks and processes in the development process.

Gorrabot is a Gitlab bot made to automate checks and processes in the Faraday development. Features Check that the CHANGELOG is modified By default, m

Faraday 7 Dec 14, 2022
Minimal Python client for the Iris API, built on top of Authlib and httpx.

🕸️ Iris Python Client Minimal Python client for the Iris API, built on top of Authlib and httpx. Installation pip install dioptra-iris-client Usage f

Dioptra 1 Jan 28, 2022
Python API for Photoshop.

Python API for Photoshop. The example above was created with Photoshop Python API.

Hal 372 Jan 02, 2023
Texting service to receive current air quality conditions and maps, powered by AirNow, Twilio, and AWS

The Air Quality Bot is generally available by texting a zip code (and optionally the word "map") to (415) 212-4229. The bot will respond with the late

Alex Laird 8 Oct 16, 2022
FAIR Enough Metrics is an API for various FAIR Metrics Tests, written in python

☑️ FAIR Enough metrics for research FAIR Enough Metrics is an API for various FAIR Metrics Tests, written in python, conforming to the specifications

Maastricht University IDS 3 Jul 06, 2022
Python CMR is an easy to use wrapper to the NASA EOSDIS Common Metadata Repository API.

This repository is a copy of jddeal/python_cmr which is no longer maintained. It has been copied here with the permission of the original author for t

NASA 9 Nov 16, 2022
📖 GitHub action schedular (cron) that posts a Hadith every hour on Twitter & Facebook.

Hadith Every Hour 📖 A bot that posts a Hadith every hour on Twitter & Facebook (Every 3 hours for now to avoid spamming) Follow on Twitter @HadithEve

Ananto 13 Dec 14, 2022
Faster Twitch Alerts is a highly customizable, lightning-fast alternative to Twitch's slow mobile notification system

Faster Twitch Alerts What is "Faster Twitch Alerts"? Faster Twitch Alerts is a highly customizable, lightning-fast alternative to Twitch's slow mobile

6 Dec 22, 2022
Acc-discord-rpc - Assetto Corsa Competizione Discord Rich Presence Client

A simple Assetto Corsa Competizione Rich Presence client. This app only works in

6 Dec 18, 2022
Official implementation of DeepSportLab (a fork of OpenPifPaf)

DeepSportLab DeepSportLab: a Unified Framework for BallDetection, Player Instance Segmentationand Pose Estimation in Team Sports Scenes This paper pre

ISPGroupUCL 8 Sep 27, 2022
A simple chat api that can also work with ipb4 and chatbox+

SimpleChatApi API for chatting that can work on its own or work with Invision Community and Chatbox+. You are also welcome to create frontend for this

Anubhav K. 1 Feb 01, 2022
An advanced telegram language translator bot

Made with Python3 (C) @FayasNoushad Copyright permission under MIT License License - https://github.com/FayasNoushad/Translator-Bot-V3/blob/main/LICE

Fayas Noushad 19 Dec 24, 2022
An unofficial API for lyricsfreak.com using django and django rest framework.

An unofficial API for lyricsfreak.com using django and django rest framework.

Hesam Norin 1 Feb 09, 2022