以下是一个示例代码,演示了如何使用API在计时器到期后重试尝试:
import requests
import time
def make_api_call(url, retries=3, delay=1):
while retries > 0:
try:
# 发送API请求
response = requests.get(url)
# 检查响应状态码
if response.status_code == 200:
return response.json()
else:
# 如果响应状态码不是200,抛出异常
response.raise_for_status()
except requests.exceptions.RequestException as e:
# 处理请求异常
print(f"请求出错: {e}")
# 减少重试次数
retries -= 1
# 等待一段时间后重试
time.sleep(delay)
# 如果重试次数耗尽,返回空
return None
# 示例调用
url = "https://api.example.com/some-endpoint"
response_data = make_api_call(url)
if response_data:
# 处理API响应数据
print(response_data)
else:
print("API请求失败")
在上述示例中,make_api_call
函数接受一个URL参数,以及可选的retries
(重试次数)和delay
(重试延迟)参数。该函数使用requests
库发送GET请求,并检查响应状态码。如果响应状态码是200,则将响应数据作为JSON返回。否则,它将抛出一个异常,并在重试次数耗尽之前进行重试。在每次重试之间,函数会使用time.sleep
函数暂停一段时间,然后再次尝试API调用。
请注意,上述示例中的重试是简单的线性重试,可以根据需要进行修改。