您可以使用自訂適配器,並對所有 HTTP/HTTPS 請求強制以指數退避因子進行多次重試。請參閱下面的範例:
import requests from requests import adapters from urllib3.util import Retry # Create a transport adapter with a custom retry strategy. retries = Retry( total=3, backoff_factor=3, status_forcelist=[500, 502, 503, 504] ) adapter = adapters.HTTPAdapter(max_retries=retries) # Ensure adapter is used for both HTTP and HTTPS requests. session = requests.Session() session.mount('https://', adapter) session.mount('http://', adapter) # Testing the retry mechanism response = session.get("http://httpbin.org/status/500")
這將傳回以下錯誤:
RetryError: HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /status/500 (Caused by ResponseError('too many 500 error responses'))
不幸的是,似乎沒有辦法知道上述機制嘗試了多少次重試,只有當所有嘗試都已用盡時
https://stackoverflow.com/a/47475019/4477547
以上是直到「requests」庫支援指數退避的自動重試的詳細內容。更多資訊請關注PHP中文網其他相關文章!