When making requests to APIs or web services with the Python Requests library, it can be beneficial to use persistent sessions. A persistent session allows you to reuse the same TCP connection for multiple requests, avoiding the overhead of establishing a new connection for every request.
Why Use Persistent Sessions?
Some key advantages of using persistent sessions in Requests:
Creating a Persistent Session
import requests
session = requests.Session()
This creates a new session object you can use for all subsequent requests:
response = session.get('https://api.example.com/v1/data')
# Session used automatically
Any custom headers, authentication, cookies or other session parameters are also retained:
session.headers.update({'X-Auth-Token': 'my-token'})
When to Use Persistent Sessions
Some good use cases:
Just be aware that sessions can consume extra TCP connections. For sporadic requests, individual requests may be preferred.