请求会话。close()不关闭会话

2024-04-27 17:07:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望对会话对象调用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()的第二次调用应该给出一个错误


Tags: 对象httpsimportcomurlclosegetis
2条回答

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将被删除。尽管如此,内部功能仍然可以发挥作用

您可以使用上下文管理器自动关闭它:

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.

相关问题 更多 >