pha*_*nny 5 python https session get python-requests
我正在尝试关闭 arequests.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()也没有抛出任何错误,这意味着它是一个有效的语法,但我不明白它到底在做什么。
在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
因此,如果我很好地理解了它的结构,那么当您关闭 a 时,您几乎与创建一个新的并将其分配给旧的Session相同。Session所以你仍然可以使用它来发送请求。
或者如果我有什么理解错误的地方,欢迎指正:D
| 归档时间: | 
 | 
| 查看次数: | 9432 次 | 
| 最近记录: |