可以使用try-except语句和while循环来实现API调用失败的重试。示例代码如下:
import requests
MAX_RETRIES = 3
def get_data_from_api(): for i in range(MAX_RETRIES): try: response = requests.get("https://example.com/api") response.raise_for_status() # 如果API调用成功,就返回response return response except requests.exceptions.RequestException: print("API调用失败,正在重试...") continue print("达到最大重试次数,API调用失败。") return None
response = get_data_from_api() if response: print("API调用成功!") # 做一些其他处理 else: print("API调用失败。")
上一篇:API调用失败