首页 > 解决方案 > 在 Python 中实现请求 api 的重试功能,无需任何库

问题描述

我正在尝试建立一个疫苗可用性项目。我每 4 秒请求一次检查疫苗剂量,

response = requests.get(https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id=770&date=)

有时我会遇到Connection Error. 我想在我的代码中添加重试功能,我知道那里有很多答案,但他们正在使用该库。我想构建自己的重试功能来了解核心机制并获得乐趣。

任何人都可以帮助它应该如何实施?

标签: pythonapiexceptionretry-logicconnectionexception

解决方案


import requests
import time
def foo():
    try:
        response = response.get("some URL")
    # you can modify exceptions as per your choice
    except Exception as e:
        time.sleep(30)
        foo()

推荐阅读