requests session.close() does not close the session

Question:

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.

Asked By: Ahtesham Akhtar

||

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.

Answered By: Mooncrater

You can use a Context Manager to auto-close it:

import requests

with requests.Session() as s:
    url = 'https://google.com'
    r = s.get(url)

See requests docs > Sessions:

This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.

Answered By: dh762
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.