在使用Python的requests庫進行網絡請求時,我們可能會遇到一些異常情況,如網絡連接錯誤、超時、HTTP錯誤等。為了確保程序的健壯性,我們需要對這些異常進行處理。以下是一些建議:
try-except語句捕獲異常:在發起請求的代碼塊周圍使用try-except語句,可以捕獲可能發生的異常。例如:
import requests
from requests.exceptions import RequestException
url = "https://api.example.com/data"
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # 如果響應狀態碼不是200,將拋出HTTPError異常
except RequestException as e:
print(f"請求發生異常:{e}")
else:
# 處理正常響應的邏輯
data = response.json()
print(data)
requests庫的異常處理函數:requests庫提供了一些內置的異常處理函數,如requests.exceptions.RequestException,可以捕獲多種網絡請求異常。在上面的示例中,我們已經使用了RequestException來捕獲異常。
如果你需要處理特定類型的異常,可以創建自定義的異常類并繼承自Exception基類。例如:
class CustomError(Exception):
pass
try:
# 你的代碼邏輯
except CustomError as e:
print(f"發生自定義錯誤:{e}")
tenacity進行重試機制:tenacity庫可以幫助你實現請求的重試機制,以應對臨時的網絡問題。首先,使用pip安裝tenacity庫:
pip install tenacity
然后,可以使用@tenacity.retry裝飾器來實現重試邏輯:
import requests
from tenacity import retry, stop_after_attempt, wait_exponential
from requests.exceptions import RequestException
url = "https://api.example.com/data"
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def make_request():
response = requests.get(url, timeout=5)
response.raise_for_status()
return response
try:
response = make_request()
data = response.json()
print(data)
except RequestException as e:
print(f"請求發生異常:{e}")
在這個示例中,我們使用tenacity庫的@retry裝飾器來設置重試策略,當請求失敗時會自動重試,最多重試3次,每次重試之間等待時間指數級增長,從4秒開始,最大不超過10秒。