How to implement retry mechanism into python requests library?

前端 未结 6 2024
春和景丽
春和景丽 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:35

    Possible solution using retrying package

    from retrying import retry
    import requests
    
    
    def retry_if_connection_error(exception):
        """ Specify an exception you need. or just True"""
        #return True
        return isinstance(exception, ConnectionError)
    
    # if exception retry with 2 second wait  
    @retry(retry_on_exception=retry_if_connection_error, wait_fixed=2000)
    def safe_request(url, **kwargs):
        return requests.get(url, **kwargs)
    
    response = safe_request('test.com')
    

提交回复
热议问题