编程语言
首页 > 编程语言> > python之requests获取响应时间(elapsed)与超时时间设置(timeout)

python之requests获取响应时间(elapsed)与超时时间设置(timeout)

作者:互联网

前言

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

当然,如果服务端没及时响应,也不能一直等着,可以设置一个timeout超时的时间。具体查看该博客:https://www.cnblogs.com/hls-code/p/14861813.html

elapsed官方文档

1、elapsed方法的官方文档地址:http://cn.python-requests.org/zh_CN/latest/api.html#requests.Response。【英文单词elapsed代表消逝得意思,可以理解为消逝得时间,混合记】

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. 简单翻译:计算的是从发送请求到服务端响应回来这段时间(也就是时间差),发送第一个数据到收到最后一个数据之间,这个时长不受响应的内容影响

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

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

elapsed方法:

获取响应时间(举例)

1、获取elapsed不同的返回值

import requests
r = requests.get("http://www.cnblogs.com/yoyoketang/")
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获取响应时间,再除1000*1000得到时间为秒的单位,当请求小于1s时,发现不出什么问题。如果时间超过1s,问题就来了。(很显然,大于1s的时候,只截取了后面的小数部分)

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

timeout超时

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

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

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

 

 

 

标签:响应,python,elapsed,seconds,时间,timeout,print,requests
来源: https://www.cnblogs.com/hls-code/p/15182011.html