python - 在 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)
解决方案
这个错误
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
推荐阅读
- powershell - Windows PowerShell ISE - 输出到文件时删除新行
- python - If、Elif 和 Else 在利润计算器应用程序中未显示正确的打印值
- awk - 当我设置 FS = " " 而不是 FS = "\t" 时,为什么 AWK 打印很奇怪?
- python - python pandas - 数据框 - 索引
- java - Apache Camel 和 Blueprint,如何在另一个捆绑包中找到一条路线?
- java - 如何从 ConstraintDescriptor::getAnnotation 获取真正的注释而不是代理?(javax.validation Apache Bval)
- javascript - Javascript - 你如何找到一个数字随时间的总增长?
- powershell - 使用 Get-StorageBlobContent 将 blob 下载到本地目录的问题
- php - 当仅在 Woocommerce 中的一个区域提供免费送货时,隐藏其他送货选项
- python-3.x - Plotly python - 将不透明度数组传递给 Scatter3d 对象中的标记