我希望调用session对象的close()来关闭会话。但看起来那是不可能的。我是不是遗漏了什么?
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)
产出:
s is closed now
<Response [200]>
对s.get()的第二个调用应该给出了一个错误。
发布于 2020-09-08 11:37:57
在Session.close()
内部,我们可以发现:
def close(self):
"""Closes all adapters and as such the session"""
for v in self.adapters.values():
v.close()
在实现内部
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()
所以我能看出的是,它清除了Session
对象的状态。因此,如果您已经登录到某个站点,并在Session
中存储了一些cookie,那么一旦使用session.close()
方法,这些cookie将被删除。尽管如此,内部功能仍然能够发挥作用。
发布于 2020-09-08 11:43:34
您可以使用上下文管理器自动关闭它:
import requests
with requests.Session() as s:
url = 'https://google.com'
r = s.get(url)
这将确保会话在with块退出后立即关闭,即使发生了未处理的异常。
https://stackoverflow.com/questions/63792435
复制相似问题