如何关闭requests.Session()? [英] How to close requests.Session()?
问题描述
我正在尝试关闭 requests.Session()
,但没有关闭.
I am trying to close a requests.Session()
but its not getting closed.
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()
也不会引发任何错误,这意味着这是一种有效的语法,但我不知道它到底在做什么.
How do I close the session? s.close()
is not throwing any error also which means it is a valid syntax but I am not understanding what exactly it is doing.
推荐答案
在请求
的源代码中, Session.close
仅关闭所有底层的 Adapter
.进一步关闭 Adapter
将清除底层的 PoolManager
.然后所有的 PoolManager
内部建立的连接将被关闭.但是,如果没有可用的连接, PoolManager
将创建一个全新的连接.
In requests
's source code, Session.close
only close all underlying Adapter
. And further closing a Adapter
is clearing underlying PoolManager
. Then all the
established connections inside this PoolManager
will be closed. But PoolManager
will create a fresh connection if there is no usable connection.
关键代码:
# 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
并将其分配给旧的一样.因此,您仍然可以使用它来发送请求.
So if I understand its structure well, when you close a Session
, you are almost the same as creating a new Session
and assign it to old one. So you can still use it to send request.
或者如果我误解了任何内容,欢迎纠正我:D
Or if I misunderstand anything, welcome to correct me :D
这篇关于如何关闭requests.Session()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!