How to implement retry mechanism into python requests library?

前端 未结 6 2020
春和景丽
春和景丽 2020-12-02 10:12

I would like to add a retry mechanism to python request library, so scripts that are using it will retry for non fatal errors.

At this moment I do consider three kin

6条回答
  •  清歌不尽
    2020-12-02 10:15

    Method to retry certain logic if some exception has occured at time intervals t1=1 sec, t2=2 sec, t3=4 sec. We can increase/decrease the time interval as well.

    MAX_RETRY = 3
    retries = 0
    
    try:
    
        call_to_api() // some business logic goes here.
    
    except Exception as exception:
    
        retries += 1
        if retries <= MAX_RETRY:
            print("ERROR=Method failed. Retrying ... #%s", retries)
            time.sleep((1 << retries) * 1) // retry happens after time as a exponent of 2
            continue
        else:
            raise Exception(exception)
    

提交回复
热议问题