深入理解Python的requests库中的timeout参数

text = requests.get(self.target_img_url, headers=headers, stream=True, verify=False, timeout=(5,5))
在Python的`requests`库中,`timeout`参数用于设置请求的超时时间。当一个请求在指定的时间内没有完成时,`requests`库会抛出一个`requests.exceptions.Timeout`异常。

`timeout`参数可以是一个单一的浮点数,也可以是一个包含两个浮点数的元组。当它是一个元组时,第一个数字是连接超时时间(connect timeout),第二个数字是读取超时时间(read timeout)。
text = requests.get(self.target_img_url, headers=headers, stream=True, verify=False, timeout=(5,5))
timeout=(5,5)`表示:

1. 连接超时时间(connect timeout):5秒
2. 读取超时时间(read timeout):5秒

这意味着,如果`requests.get()`在5秒内无法建立连接,或者在5秒内无法完成读取操作,它将抛出一个`requests.exceptions.Timeout`异常。

下面是一个简单的例子来说明这个超时设置是如何工作的:
import requests
import time

url = "http://example.com"  # 假设这是一个非常慢的服务器,需要10秒才能响应
headers = {}

try:
    response = requests.get(url, headers=headers, stream=True, verify=False, timeout=(5,5))
    response.raise_for_status()  # 如果响应状态码不是200,则抛出异常
    print("Success!")
except requests.exceptions.Timeout:
    print("Request timed out!")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
在这个例子中,由于服务器的响应时间超过了设定的超时时间(5秒),所以会捕获到`requests.exceptions.Timeout`异常并打印"Request timed out!"。如果服务器响应很快,那么它会打印"Success!"。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值