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

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)

 响应结果

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

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

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

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

 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)

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