The simplest method is to use the tenacity package:

def stop_after_7_attempts():
    print("Stopping after 7 attempts")
    raise Exception
def stop_after_10_s():
    print("Stopping after 10 seconds")
    raise Exception
@retry(wait=wait_random(min=1, max=2))
def wait_random_1_to_2_s():
    print("Randomly wait 1 to 2 seconds between retries")
    raise Exception
@retry(wait=wait_exponential(multiplier=1, min=4, max=10))
def wait_exponential_1():
    print("Wait 2^x * 1 second between each retry starting with 4 seconds, then up to 10 seconds, then 10 seconds afterwards")
    raise Exception

Related Posts

  • Making a unique list in Python preserving the order
  • Sorting a Python dict by value
  • Annotate Querysets to Fetch Specific Values
  • Optimize Database Calls with Prefetch Related and Select Related
  • Testing exceptions in pytest