通过循环重用会话中使用的相同连接

Reusing the same connection used within a session with a loop

我只想询问有关在循环发送相同 POST 请求时重用相同连接的问题。假设我有这个代码:

import requests
import time
r = requests.Session()
url = "http://somenumbers.php"
while True:
    x = r.post(url)
    time.sleep(10)

现在按照documentation of requests library

Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection! Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set stream to False or read the content property of the Response object

这对上面的代码有效吗?我试图防止在服务器冻结或发生读取超时的情况下发送相同的请求。在 中,我回顾了整个问题,其中一个建议是重用连接,但是

r.post 是阻塞调用。一旦发送请求并收到响应,该函数将仅 return 。只要您在循环终止之前访问 x.content,下一个循环将重新使用底层 TCP 连接。

Isn't sending the same request on the same connection will just mean multiple entries, or is it going to fix the issue since it will only pull back when one entry is sent as the documentation states?

requests 不缓存响应。它不会检查是否发出了具有相同参数的先前请求。如果你需要它,你将不得不自己构建一些东西。

won't that affect performance and cause long delays since the request is trapped inside the connection

requests 只会重新使用一个可用的连接。如果不存在空闲连接,将建立一个新连接。您可以使用 requests.packages.urllib3.poolmanager.PoolManager 来控制池中的连接数。