python接口自动化(十七) requests获取响应时间(elapsed)与超时(timeout)

前言

requests发请求时,接口的响应时间,也是我们需要关注的一个点,如果响应时间太长,也是不合理的。

如果服务端没及时响应,也不能一直等着,可以设置一个timeout超时的时间。

elapsed官方文档

1.elapsed方法的官方文档地址:http://cn.python-requests.org/zh_CN/latest/api.html#requests.Response

elapsed = None
The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.


 从发送请求到响应到达之间经过的时间量(以时间增量表示)。此属性专门度量从发送请求的第一个字节到完成对头的解析所用的时间。因此,它不受使用响应内容或stream关键字参数值的影响。 

2.用help()查看elapsed里面的方法

import requests
r=requests.get("https://www.baidu.com")
print(help(r.elapsed))

 elapsed里面几个方法介绍

  • total_seconds 总时长,单位秒
  • microseconds: Number of microseconds (>= 0 and less than 1 second)  获取微妙部分,大于0小于1秒
  • seconds:Number of seconds (>= 0 and less than 1 day)  秒,大于0小于1天
  • max = datetime.timedelta(days=999999999, seconds=86399, microseconds=9. 最大时间
  • min = datetime.timedelta(days=-999999999)  最小时间
  • resolution = datetime.timedelta(microseconds=1) 最小时间单位

获取响应时间

1.获取elapsed不同的返回值

import requests
r=requests.get("https://www.baidu.com")
print(r.elapsed)
print(r.elapsed.total_seconds())
print(r.elapsed.microseconds)
print(r.elapsed.seconds)
print(r.elapsed.days)
print(r.elapsed.max)
print(r.elapsed.min)
print(r.elapsed.resolution)

 响应结果

2.网上很多资料写的是用microseconds获取响应时间,当请求小于1s时,发现不出什么问题,如果时间超过1s,问题就来了。

(很显然,大于1s的时候,只截取了后面的小数部分)

 3.所以获取响应时间的正确姿势应该是:r.elapsed.total_seconds(),单位是s

 timeout超时

1.如果一个请求响应时间比较长,不能一直等着,可以设置一个超时时间,让它抛出异常。

2.如下请求,设置超时为1s,那么就会抛出这个异常:requests.exceptions.ConnectionError: HTTPSConnectionPool

import requests
a=requests.get("http://cn.python-requests.org/zh_CN/latest/",timeout=1)
print(a.elapsed)
print(a.elapsed.total_seconds())
print(a.elapsed.microseconds)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值