Python urllib3 : close idle connection after some time

标签 python http tcp keep-alive urllib3

有没有办法告诉 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/

    相关文章:

    Python分区函数需要优化

    python - 在 2 元组的 python zip() 列表上使用 urllib.parse.urlencode()

    rest - HTTP 方法名称 : upper or lower case?

    http - API 总是错误 408 - 发送的数据类型无效

    Javascript - 网页内容转字符串

    c - 通过c中的套接字从结构传递字符

    python - App Engine 中是否有 "children"方法?

    android - 写入 VpnService 输出流没有响应

    c++ - sfml 中已连接客户端的端口

    函数内外的Python全局列表修改