Tenacity retry module understanding

441 Views Asked by At

I have written multiple except cases at the end of the code. Can anyone explain exactly whats wrong with my code, whats the correct way to use tenacity ?

also I coulnt understand the use of reraise = True and False.

import requests
from tenacity import retry, stop_after_attempt, wait_exponential, RetryError, wait_fixed, retry_if_exception_type, after, before
from urllib3.exceptions import ConnectTimeoutError, MaxRetryError


def log_attempt_number(retry_state):
    """return the result of the last call attempt"""
    print(f"attempt {retry_state.attempt_number} failed,will try once more.")


def log_before(retry_state):
    print(f"starting to attempt for {retry_state.attempt_number} time")

# Define the retry decorator
@retry(
    reraise = True,
    retry = retry_if_exception_type(),
    stop=stop_after_attempt(3), # Maximum number of retries
    wait=wait_fixed(3),
    before=log_before,
    after=log_attempt_number
)
def make_request(data):
    response = requests.get('http://localhost:8888/', timeout=0.1)
    response.raise_for_status()
    return response


def fun():
    try:
        response = make_request({ 'key': 'value' })
        print(f'SUCCESS: {response}')

    except requests.RequestException as e:
        print(f'FAILED: {e}')

    except ConnectTimeoutError as e:
        print(f'FAILED 2: {e}')

    except MaxRetryError as e:
        print(f'FAILED 3: {e}')

    except RetryError as e:
        print(f'FAILED 4: {e}')

    print("[REACHED HERE]")
    print(make_request.retry.statistics)

fun()

I am just exploring on how to use retry module tenacity. And wrote this part of code.

0

There are 0 best solutions below