How do you add retries with exponential backoff to `requests`?
IntermediateConceptData formats, HTTP & REST APIs
Answer
Mount an HTTPAdapter configured with urllib3's Retry:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=5, connect=5, read=3, backoff_factor=0.5,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}),
respect_retry_after_header=True)
s = requests.Session()
s.mount("https://", HTTPAdapter(max_retries=retry, pool_maxsize=20))
Backoff grows as backoff_factor * 2 ** (retry - 1), capped by backoff_max. POST is excluded by default because it is not idempotent.
More on Data formats, HTTP & REST APIs
How do you read and write JSON, and what are the common gotchas?BeginnerWhy must you use `yaml.safe_load` rather than `yaml.load`?BeginnerHow do you load a multi-document Kubernetes YAML file?IntermediateHow do you read and write CSV files properly?BeginnerHow do you make an HTTP request with `requests` the right way?BeginnerWhy use a `requests.Session`?Intermediate