2024-04-27 17:07:53 发布
网友
我希望对会话对象调用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现在关门了 <;答复[200]>
对s.get()的第二次调用应该给出一个错误
在implementation for ^{}中,我们可以发现:
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.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()
所以我能理解的是,它清除了Session对象的状态。因此,如果您登录到某个站点并且在Session中存储了一些cookie,那么一旦您使用session.close()方法,这些cookie将被删除。尽管如此,内部功能仍然可以发挥作用
Session
session.close()
您可以使用上下文管理器自动关闭它:
import requests with requests.Session() as s: url = 'https://google.com' r = s.get(url)
见requests docs > Sessions:
This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.
在implementation for ^{} 中,我们可以发现:
在^{} implementation 内:
所以我能理解的是,它清除了
Session
对象的状态。因此,如果您登录到某个站点并且在Session
中存储了一些cookie,那么一旦您使用session.close()
方法,这些cookie将被删除。尽管如此,内部功能仍然可以发挥作用您可以使用上下文管理器自动关闭它:
见requests docs > Sessions:
相关问题 更多 >
编程相关推荐