網絡請求往往會有很多不受控制的意外情況發生,有時候我們要讓它let it crash
,有時候我們想多嘗試幾次。
以前,使用retry
策略,我一般會使用tenacity
1這個第三方庫。這個庫的API相當得漂亮,很多大V也推薦過。
最近,我看了一篇文章2,是requests
的作者之一寫的。他告訴我們,requests
原生就支持retry。
在urllib3中使用retry
urllib3
使用PoolManager
,可以對特定的response設置retry。
比如,下面我們對500錯誤進行了retry:
from urllib3.util import Retry
from urllib3 import PoolManager
retries = Retry(total=5, status_forcelist=[500])
manager = PoolManager(retries=retries)
response = manager.request('GET', 'https://httpbin.org/status/500')
在requests中使用retry
from requests.packages.urllib3.util import Retry
from requests.adapters import HTTPAdapter
from requests import Session, exceptions
s = Session()
s.mount('https://', HTTPAdapter(
max_retries=Retry(total=5, status_forcelist=[500])
)
)
s.get('https://httpbin.org/status/500')
可以看到requests
的API一貫的簡潔。另外需要知道的是這里利用了requests
的"傳輸適配器(Transport Adapter)",如果你對這個不了解,請看這篇博客3.