Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requests session.close() does not close the session

I expected calling close() on a Session object to close the session. But looks like that's not happening. Am I missing something?

import requests
s = requests.Session()
url = 'https://google.com'
r = s.get(url)
s.close()
print("s is closed now")
r = s.get(url)
print(r)

output:

s is closed now
<Response [200]>

The second call to s.get() should have given an error.

like image 427
Ahtesham Akhtar Avatar asked Oct 31 '25 11:10

Ahtesham Akhtar


1 Answers

Inside the implementation for Session.close() we can find that:

def close(self):
    """Closes all adapters and as such the session"""
    for v in self.adapters.values():
        v.close()

And inside the adapter.close implementation:

   def close(self):
        """Disposes of any internal state.

        Currently, this closes the PoolManager and any active ProxyManager,
        which closes any pooled connections.
        """
        self.poolmanager.clear()
        for proxy in self.proxy_manager.values():
            proxy.clear()

So what I could make out is that, it clears the state of the Session object. So in case you have logged in to some site and have some stored cookies in the Session, then these cookies will be removed once you use the session.close() method. The inner functions still remain functional though.

like image 69
Mooncrater Avatar answered Nov 02 '25 00:11

Mooncrater