设置请求的最大重试次数。post

2024-04-25 14:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对脚本设置最大重试限制以消除以下错误:

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)

Tags: inimporttxtoutputifwithlinepass
1条回答
网友
1楼 · 发布于 2024-04-25 14:40:33

这个错误

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'))

是由于向服务器发送太多请求而导致的,检测的唯一方法是服务器端的响应,即无法知道何时会在客户端引发此错误

有几种方法可以避免这个错误

你可以抓住错误,打破循环

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

相关问题 更多 >