How to implement retry mechanism into python requests library?

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

    This snippet of code will make all HTTP requests from the same session retry for a total of 5 times, sleeping between retries with an increasing backoff of 0s, 2s, 4s, 8s, 16s (the first retry is done immediately). It will retry on basic connectivity issues (including DNS lookup failures), and HTTP status codes of 502, 503 and 504.

    import logging
    import requests
    
    from requests.adapters import HTTPAdapter
    from requests.packages.urllib3.util.retry import Retry
    
    logging.basicConfig(level=logging.DEBUG)
    
    s = requests.Session()
    retries = Retry(total=5, backoff_factor=1, status_forcelist=[ 502, 503, 504 ])
    s.mount('http://', HTTPAdapter(max_retries=retries))
    
    s.get("http://httpstat.us/503")
    

    See Retry class for details.

提交回复
热议问题