Created
September 30, 2020 20:43
-
-
Save mariocesar/cd51bfea0f16f14385874a5e06aa9822 to your computer and use it in GitHub Desktop.
Python requests timeout retry
This file contains 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
import requests | |
from requests.adapters import Retry, HTTPAdapter | |
class RetryTimeoutAdapter(HTTPAdapter): | |
def __init__(self): | |
max_retries = Retry( | |
total=3, | |
backoff_factor=1, | |
status_forcelist=[500, 502, 503, 504], | |
method_whitelist=["GET", "HEAD", "INFO"], | |
) | |
super().__init__(max_retries=max_retries) | |
class Session(requests.Session): | |
def __init__(self): | |
super().__init__() | |
self.mount("https://", RetryTimeoutAdapter()) | |
self.mount("http://", RetryTimeoutAdapter()) | |
self.headers.update( | |
{ | |
"Pragma": "no-cache", | |
"Cache-Control": "no-cache", | |
} | |
) | |
with Session() as session: | |
response = session.get("myurltotimeout") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment