如何关闭请求。会话()?

2024-04-19 21:39:20 发布

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

我试图关闭requests.Session(),但它没有关闭。在

s = requests.Session()
s.verify = 'cert.pem'
res1 = s.get("https://<ip>:<port>/<route>")
s.close() #Not working
res2 = s.get("https://<ip>:<port>/<route>") # this is still working which means s.close() didn't work.

如何关闭会话?s.close()没有抛出任何错误,这也意味着它是一个有效的语法,但我不知道它到底在做什么。在


Tags: httpsipclosegetcertportsessionnot
1条回答
网友
1楼 · 发布于 2024-04-19 21:39:20

requests的源代码中,Session.close只关闭所有底层Adapter。进一步关闭Adapter是在清除底层的PoolManager。然后所有的 此PoolManager内建立的连接将被关闭。但是如果没有可用的连接,PoolManager将创建一个新的连接。在

关键代码:

# requests.Session
def close(self):
    """Closes all adapters and as such the session"""
    for v in self.adapters.values():
        v.close()

# requests.adapters.HTTPAdapter
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()

# urllib3.poolmanager.PoolManager
def connection_from_pool_key(self, pool_key, request_context=None):
    """
    Get a :class:`ConnectionPool` based on the provided pool key.

    ``pool_key`` should be a namedtuple that only contains immutable
    objects. At a minimum it must have the ``scheme``, ``host``, and
    ``port`` fields.
    """
    with self.pools.lock:
        # If the scheme, host, or port doesn't match existing open
        # connections, open a new ConnectionPool.
        pool = self.pools.get(pool_key)
        if pool:
            return pool

        # Make a fresh ConnectionPool of the desired type
        scheme = request_context['scheme']
        host = request_context['host']
        port = request_context['port']
        pool = self._new_pool(scheme, host, port, request_context=request_context)
        self.pools[pool_key] = pool

    return pool

所以如果我很好地理解它的结构,当你关闭一个Session时,你几乎和创建一个新的Session并将其分配给旧的一样。所以你仍然可以用它来发送请求。在

或者如果我误解了什么,欢迎纠正我:D

相关问题 更多 >