Tenacity
Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything. It originates from a fork of retrying which is sadly no longer maintained.
Под Вашу задачу, это будет выглядеть примерно так:
import requests
from tenacity import retry, stop_after_attempt, wait_fixed
@retry(stop=stop_after_attempt(3), wait=wait_fixed(3))
def fetch():
res = requests.get("https://site.ru")
# res = requests.get("https://site.ru", params={"key": "value"})
if res.status_code != 200:
raise requests.exceptions.HTTPError(res.status_code)
data = res.json()
return data
# return data["link"]
print(fetch())
-
wait=wait_fixed(3)
- ждать 2 секунды между попытками.
-
stop=stop_after_attempt(3)
- остановка после 3х попыток.