如何使用请求库实现重试
How to implement retry with requests library
所以我有这段代码
statssession = requests.Session()
getstats = statssession.get('https://api.hypixel.net/player',
params={'key': random.choice([key, key2]), 'uuid': playeruuid},
timeout=10).json()
我是 python 的新手,没有 OOP 经验,这段代码会引发随机读取的随机超时异常。我想要的是,当它抛出该异常时,不仅会破坏我的代码,而且最好使用请求本身的库重试请求,但我不知道该怎么做,所以我在这里问,感谢任何帮助。
您似乎错误地使用了 API:https://api.hypixel.net/#section/Authentication/ApiKey
尝试将密钥设置为 requests.Session
headers:
statssession = requests.Session()
statssession.headers["API-Key"] = random.choice([key, key2])
要在超时后重试,您可以使用 try except
块:
for _ in range(5):
try:
getstats = statssession.get(
'https://api.hypixel.net/player',
params = {'uuid': playeruuid},
timeout=10).json()
break
except requests.exceptions.ReadTimeout:
continue
或者您可以在 urllib3
内设置重试次数,由 requests
使用,如下所述:Can I set max_retries for requests.request?
statssession = requests.Session()
getstats = statssession.get('https://api.hypixel.net/player',
params={'key': random.choice([key, key2]), 'uuid': playeruuid},
timeout=10).json()
我是 python 的新手,没有 OOP 经验,这段代码会引发随机读取的随机超时异常。我想要的是,当它抛出该异常时,不仅会破坏我的代码,而且最好使用请求本身的库重试请求,但我不知道该怎么做,所以我在这里问,感谢任何帮助。
您似乎错误地使用了 API:https://api.hypixel.net/#section/Authentication/ApiKey
尝试将密钥设置为 requests.Session
headers:
statssession = requests.Session()
statssession.headers["API-Key"] = random.choice([key, key2])
要在超时后重试,您可以使用 try except
块:
for _ in range(5):
try:
getstats = statssession.get(
'https://api.hypixel.net/player',
params = {'uuid': playeruuid},
timeout=10).json()
break
except requests.exceptions.ReadTimeout:
continue
或者您可以在 urllib3
内设置重试次数,由 requests
使用,如下所述:Can I set max_retries for requests.request?