Problem Statement
Explain why you would use requests.Session in a production client and how you would add retries.
Explanation
A Session keeps TCP connections open between calls. This cuts handshake overhead and improves throughput. It also centralizes shared headers, cookies, and auth, making code cleaner and reducing duplication.
To add retries, mount an HTTPAdapter with a Retry policy from urllib3. Configure backoff, allowed methods, and status codes like 429 or 503. This gives robust behavior under transient failures without rewriting call sites.
Code Solution
SolutionRead Only
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
s=requests.Session()
retry=Retry(total=3, backoff_factor=0.5, status_forcelist=[429,502,503,504])
s.mount('https://', HTTPAdapter(max_retries=retry))Practice Sets
This question appears in the following practice sets:
