In [1]:
import retry
import requests
import random
import sys

In [2]:
class UnreliableException(Exception):
    def __init__(self, message):
        self.message = message
        
    def _render_traceback_(self):
        return ['UnreliableException: ' + self.message]

    
class ControlFlowException(Exception):
    def __init__(self, message):
        self.message = message
        
    def _render_traceback_(self):
        return ['ControlFlowException: ' + self.message]

In [3]:
def make_unreliable_request():
    if 0 == random.choice(range(2)):
        return requests.get('https://blockchain.info/tobtc?currency=USD&value=500')
    else:
        raise UnreliableException("Things don't always go the way you want ")

make_unreliable_request()


Out[3]:
<Response [200]>

In [4]:
make_unreliable_request()


UnreliableException: Things don't always go the way you want 

In [5]:
@retry.retry()
def reliable_request():
    return make_unreliable_request()

reliable_request()


Out[5]:
<Response [200]>

In [8]:
def make_unreliable_request2():
    if 0 == random.choice(range(2)):
        return requests.get('https://blockchain.info/tobtc?currency=USD&value=500')
    else:
        if random.choice(range(2)) == 0:
            raise UnreliableException("Things don't always go the way you want ")
        else:
            raise ControlFlowException("Bubble me up Scotty")


@retry.retry(UnreliableException)
def reliable_request2():
    return make_unreliable_request2()
reliable_request2()


Out[8]:
<Response [200]>

In [12]:
reliable_request2()


ControlFlowException: Bubble me up Scotty

In [14]:
import logging
logging.basicConfig()

def make_unreliable_request3():
    choice = random.choice(range(4))
    if 0 == choice:
        return requests.get('https://blockchain.info/tobtc?currency=USD&value=500')
    else:
        raise UnreliableException("Things don't always go the way you want ")

@retry.retry(UnreliableException, delay=1, backoff=2)
def reliable_request():
    return make_unreliable_request3()

reliable_request()


WARNING:retry.api:Things don't always go the way you want , retrying in 1 seconds...
WARNING:retry.api:Things don't always go the way you want , retrying in 2 seconds...
WARNING:retry.api:Things don't always go the way you want , retrying in 4 seconds...
Out[14]:
<Response [200]>

In [16]:
reliable_request()


WARNING:retry.api:Things don't always go the way you want , retrying in 1 seconds...
WARNING:retry.api:Things don't always go the way you want , retrying in 2 seconds...
WARNING:retry.api:Things don't always go the way you want , retrying in 4 seconds...
WARNING:retry.api:Things don't always go the way you want , retrying in 8 seconds...
Out[16]:
<Response [200]>

In [ ]: