Ad

How To Implement Retry With Requests Library

- 1 answer

enter image description hereSo i have this bit of code

statssession = requests.Session()
getstats = statssession.get('https://api.hypixel.net/player',
                                                params={'key': random.choice([key, key2]), 'uuid': playeruuid},
                                                timeout=10).json()

I'm completely new to python with no OOP experience and this bit of code throws a random time out exception for read randomly. What I want is when it throws that exception to not just break my code but retry the request instead preferably with the library from requests itself but I have no idea how to do it so here I'm asking, any help appreciated.

Ad

Answer

It looks like you're using the API incorrectly: https://api.hypixel.net/#section/Authentication/ApiKey

Try setting the key into the requests.Session headers:

statssession = requests.Session()
statssession.headers["API-Key"] = random.choice([key, key2])

To try again after timeout, you can use a try except block:

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

Or you can set retries within urllib3, used by requests, as outlined here: Can I set max_retries for requests.request?

Ad
source: stackoverflow.com
Ad