requests sessions in Python
Reusing connections, headers, and cookies across calls.
import requests
session = requests.Session()
session.headers.update({"User-Agent": "typestar-bot/1.0"})
login = session.post(
"https://example.com/login",
data={"user": "ada", "password": "secret"},
timeout=10,
)
profile = session.get("https://example.com/profile", timeout=10)
cookies = session.cookies.get_dict()
session.close()
How it works
- A
Sessionpersists headers for every request. - Logging in stores cookies on the session.
- Later requests reuse them automatically.
The run, in numbers
- Lines
- 14
- Characters to type
- 333
- Tokens
- 88
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.
Step 3 of 5 in requests, step 3 of 9 in Web scraping.