记住:
连接池是维护的数据库连接的缓存
当将来请求时,可以“重用”连接
需要数据库。
你可以通过多种方式做到这一点(我猜):
如果一次失败,这会中断您的连接。设置它:
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))
他:班级:~connectionpool.ConnectionPool
类保留一个个体池:类:~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) 策略来丢弃旧池。也就是说,如果您设置 PoolManagernum_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/')
另外,文档说:
陈旧池的清理不会立即发生。
所以对于那个用途最近使用的容器 https://urllib3.readthedocs.io/en/1.3/collections.html#urllib3._collections.RecentlyUsedContainer(文档仅包含一行)。
Note:
如果 PoolManager 影响所有连接的池,则设置参数
从而。
希望这对您有帮助。获取高级使用文档HERE https://github.com/urllib3/urllib3/blob/master/docs/advanced-usage.rst .