Last active
November 9, 2023 01:05
-
-
Save datashaman/a517da0ebfe7939c6b83 to your computer and use it in GitHub Desktop.
More succinct resilient session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from requests import Session | |
import time | |
class ResilientSession(Session): | |
""" | |
This class is supposed to retry requests that return temporary errors. | |
At this moment it supports: 502, 503, 504 | |
""" | |
def request(self, method, url, **kwargs): | |
counter = 0 | |
while True: | |
counter += 1 | |
r = super(ResilientSession, self).request(method, url, **kwargs) | |
if r.status_code in [ 502, 503, 504 ]: | |
delay = 10 * counter | |
logging.warn("Got recoverable error [%s] from %s %s, retry #%s in %ss" % (r.status_code, method, url, counter, delay)) | |
time.sleep(delay) | |
continue | |
return r | |
if __name__ == '__main__': | |
s = ResilientSession() | |
s.get('http://httpstat.us/502') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you need to add the exit clause for the while loop... at least I had to do it to get it working:
The last else is to cover for all other status codes