Why use a `requests.Session`?
IntermediateConceptData formats, HTTP & REST APIs
Answer
A Session reuses TCP and TLS connections through a connection pool (huge latency win for many calls to the same host), keeps default headers and auth in one place, persists cookies, and is where you mount retry adapters.
s = requests.Session()
s.headers.update({"Authorization": f"Bearer {token}", "User-Agent": "ops-bot/1.0"})
for repo in repos:
s.get(f"https://api.github.com/repos/acme/{repo}", timeout=10)
Sessions are generally used per thread; sharing one across threads usually works but is not officially guaranteed thread-safe.
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?BeginnerHow do you add retries with exponential backoff to `requests`?Intermediate