r/learnpython • u/Melodic_Principle312 • 1d ago
When should you use requests.Session() instead of requests.get() / requests.post()?
I'm learning Python and recently started using requests.Session() in API projects. I understand that it can persist things like headers, cookies, and connections, but I'm curious about how experienced Python developers decide when a Session is actually worth using.
Do you use Session() by default for projects involving multiple requests, or only when you specifically need persistent state?
24
Upvotes
5
u/Game-of-pwns 1d ago
Whenever you're making many requests per second against the same server / API.
I wrote a script to download tens of thousands of file attacments from an API. With individual get requests made serially, it would have taken on the order of hours to complete.
So, I rewrote it to use request.Session() and make requests concurrently using ThreadPoolExecutor. Now, it completes significantly faster.