Add retry with exponential backoff to HTTP calls without writing the loop yourself.
IntermediateHands-onPython for DevOps
Answer
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=5,
backoff_factor=1, # sleeps grow exponentially between attempts
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "PUT", "DELETE"],
respect_retry_after_header=True,
)
s = requests.Session()
s.mount("https://", HTTPAdapter(max_retries=retry))
resp = s.get("https://api.example.com/items", timeout=5)
Key trick → POST is left out of allowed_methods on purpose, because retrying a non-idempotent call can create duplicates. Retry-After is honoured for 429s.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.IntermediateRun a shell command from Python, capture output, and fail properly on error.Intermediate