首页 > 解决方案 > 在 requests.post 上设置最大重试次数

问题描述

我想在我的脚本上设置最大重试限制以消除这些错误:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='173.180.119.132', port=8080): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03F9E2E0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

我找不到post以最大重试次数发送请求的方法。

这是我的代码:

import requests
from requests.adapters import HTTPAdapter
requests.adapters.DEFAULT_RETRIES = 2
f = open("hosts.txt", "r")

payload = {
    'inUserName': 'ADMIN',
    'inUserPassword': '1234'
}
i = 0
for line in f:
    i += 1
    print(i)
    r = requests.post("http://" + line, data=payload)
    if "401 - Unauthorized" in r:
        pass
    else:
        if r.status_code != 200:
            pass
        else:
            with open("output.txt", "a+") as output_file:
                output_file.write(line)

标签: python

解决方案


这个错误

requests.exceptions.ConnectionError: HTTPConnectionPool(host='173.180.119.132', port=8080): Max retries exceeded with url: / (由 NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03F9E2E0>: 无法建立新的连接:[WinError 10061] 无法建立连接,因为目标机器主动拒绝它'))

是由向服务器发送太多请求引起的,唯一检测方法是通过服务器端的响应,即无法知道何时会在客户端抛出此错误。

有几种方法可以解决此错误。

您可以捕获错误并跳出循环。

try:
    page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
    #r.status_code = "Connection refused"
    break

您还可以简单地sleep(unit)在代码中添加一行,以在对服务器的每个请求之间添加一个间隙。这通常可以克服maxRetry错误。

from time import sleep
sleep(5) # 5 seconds sleep cmd

推荐阅读