天天看点

python接口测试之requests如何设置超时,并抛出异常

1、timeout仅对连接过程有效(没有从基础套接字中接受到任何字节数据的时候),与响应体的下载无关。

#-*- coding:utf-8 -*-
import requests

response = requests.get("https://api.github.com/user/emails",timeout=0.1, auth=('username', 'password'))
           

2、使用timeout参数,可以设置等待连接的秒数,如果等待时间超时,requests会抛出异常,看起来像程序执行错误,使用RequestException可以处理

#-*- coding:utf-8 -*-
import requests
from requests import exceptions

try:
	response = requests.get("https://api.github.com/user/emails",timeout=0.1, auth=('username', 'password'))
except exceptions.Timeout as e:
	print(str(e))
else:
	print(response.text)
	
           

HTTPSConnectionPool(host='api.github.com', port=443): Read timed out. (read timeout=0.1)