有没有办法告诉 Python urllib3 在一段时间后不要重用空闲连接,而是关闭它们?
在看 https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool似乎没有显示任何相关内容。
最佳答案
记住:
A connection pool is a cache of database connections maintained so that the connections can be "reused" when future requests to the database are required.
您可以通过多种方式做到这一点(我猜):
如果一次失败,这会中断您的连接。要设置它:
import requests
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=1) # is zero for default
s.mount('http://', a)
“pool_connections”是要保留的主机池的数量。例如,如果您连接到 100 个不同的主机,并且
pool_connections=10
,那么只会重新使用最近的 10 个主机的连接。要设置:s = requests.Session()
s.mount('https://', HTTPAdapter(pool_connections=1))
s.get('https://www.example.com')
这将停止池的重用。
仅当您在多线程环境中使用 Session 时才需要注意这一点。要设置它:
s = requests.Session()
s.mount('https://', HTTPAdapter(pool_connections=1, pool_maxsize=1))
他 :class:
~connectionpool.ConnectionPool
类(class)保持个人池:类(class):~connection.HTTPConnection
实例。这些连接在单个请求期间使用,并在请求完成时返回到池中。默认情况下,只会保存一个连接以供重复使用。要设置它(默认情况下是这样):from urllib3 import HTTPConnectionPool
pool = HTTPConnectionPool('www.example.com', maxsize=0) #likely to slow you down cuz it never stores the pools
maxsize – 可以重用的要保存的连接数。多于 1 在多线程情况下很有用。
PoolManager 使用最近最少使用 (LRU) 策略来丢弃旧池。也就是说,如果你设置了 PoolManager
num_pools
到 10,然后在向 11 个或更多不同的主机发出请求后,最终将清理最近最少使用的池。所以要做到这一点:from urllib3 import PoolManager
manager = PoolManager(1) # not the manager cleans up pools used for one time
r = manager.request('GET', 'http://www.example.com/')
此外,文档说:
Cleanup of stale pools does not happen immediately.
所以为此使用 RecentlyUsedContainer (文档仅包含一行)。
笔记:
Setting arguments if PoolManager affects all the pools connected thereby.
希望这对你有帮助。获取高级使用文档 HERE .
关于Python urllib3 : close idle connection after some time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345555/