Reputation: 303
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.
Upvotes: 4
Views: 2047
Reputation: 2429
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)
This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.
Upvotes: -1
Reputation: 4861
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.
Upvotes: 3