ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

requests超时重试方法(由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败)

2022-04-12 13:01:48  阅读:335  来源: 互联网

标签:方在 www github url 重试 requests com 连接


[requests超时重试方法(由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败) - 习久性成 - 博客园](https://www.cnblogs.com/hls-code/p/15184580.html)

前言

1、"由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败",这是在做接口测试经常遇到的问题。

2、异常信息:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000020F06524AC8>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))

3、一般出现这个问题的原因是:host='www.github.com' 主机地址没连上;比如使用 requests 发请求时,有些网站服务器不稳定,特别是国外的网站,经常会出现连接失败情况。

连接失败后,有时候会抛出上面异常;有时候会一直卡住,进入假死状态,没响应,也不会结束。

timeout参数

requests 发请求的时候会有个默认的超时时间,这个时间在20秒左右。

复制代码
import requests

s = requests.session()

url = "https://www.github.com/"
r = s.request("GET", url=url)
print(r.text)
复制代码

连不上服务器会出现异常: requests.exceptions.ConnectionError 

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000020F06524AC8>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))

如果请求一直没响应,进入假死状态,可以加个 timeout 超时时间,达到这个请求超时时间就结束,如 15 秒超时。

复制代码
import requests

s = requests.session()

url = "https://www.github.com/"
r = s.request("GET", url=url, timeout=15)
print(r.text)
复制代码

这样抛出的异常是: requests.exceptions.ConnectTimeout 

raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000001CF6D2A4A20>, 'Connection to www.github.com timed out. (connect timeout=15)'))

失败重试 max_retries

Requests 自带了一个传输适配器,也就是 HTTPAdapter

这个适配器使用了强大的 urllib3,为 Requests 提供了默认的 HTTP 和 HTTPS 交互
每当 Session 被初始化,就会有适配器附着在 Session 上,其中一个供 HTTP 使用,另一个供 HTTPS 使用。

复制代码
import requests
from requests.adapters import HTTPAdapter

s = requests.session()


# max_retries=3 重试3次
s.mount('http://', HTTPAdapter(max_retries=3))
s.mount('https://', HTTPAdapter(max_retries=3))


url = "https://www.github.com/"
r = s.request("GET", url=url, timeout=15)
print(r.text)
复制代码

这样每次请求超时15s,超时后会重试3次,最大请求时长45s。

去期待陌生,去拥抱惊喜。

标签:方在,www,github,url,重试,requests,com,连接
来源: https://www.cnblogs.com/ministep/p/16134568.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有