# 导入 requests 库
import requests
# 导入 requests.exceptions 库
from requests.exceptions import (
ConnectTimeout,
HTTPError,
ReadTimeout,
Timeout,
ConnectionError
)
# 定义一个超时时间,单位是秒
timeout = 10
# 定义一个重试次数
max_retries = 3
# 定义一个重试策略,可以根据需要修改
retry_strategy = requests.packages.urllib3.util.retry.Retry(
total=max_retries,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
method_whitelist=["HEAD", "GET", "OPTIONS"]
)
# 创建一个适配器,使用重试策略
adapter = requests.adapters.HTTPAdapter(max_retries=retry_strategy)
# 创建一个会话,使用适配器
session = requests.Session()
session.mount("https://", adapter)
session.mount("http://", adapter)
# 使用会话的 request 方法来发送请求,设置超时时间
try:
resp = session.request("POST", url, json=data, headers=self.auth_header, timeout=timeout)
except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError) as e:
# 处理异常
print(e)
else:
# 处理正常响应
print(resp.status_code)