ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

requests---timeout请求超时

2021-01-24 15:30:41  阅读:141  来源: 互联网

标签:-% 请求 --- timeout time print requests localtime


  我们在接口测试的时候,如果因为一些原因,服务器没有给我们响应,我们这边就要在这等着,为了避免等待时间过长,我们可以在请求中加入一个超时时间,毕竟我们每天上班时间这么少,不能一直等下去~

timeout

requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。如果不使用,你的程序可能会永远等待响应

用法:直接在请求框中加入timeout=XX值

小试牛刀

安静请求谷歌搜索服务,因为需要翻墙,这里会请求失败,我们通过for循环多次请求并用rty来捕捉错误异常

# coding:utf-8
import requests
import time
url = 'https://www.google.com/?hl=zh_CN'
t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('开始时间:'+t1)
for i in range(1,3):
    try:
        r = requests.get(url,timeout=5)
        t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print("请求成功,请求时间是:{}".format(t2))
    except Exception as e:
        t3 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print("请求失败,请求时间是:{}".format(t3))
        print('失败原因:%s'%e)

 

这里可以通过查看请求的时间差看出,5秒过后就报出异常

如果不加timeout限制的,看看请求时间为多长

# coding:utf-8
import requests
import time
url = 'https://www.google.com/?hl=zh_CN'
t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('开始时间:'+t1)
for i in range(1,3):
    try:
        r = requests.get(url)
        t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print("请求成功,请求时间是:{}".format(t2))
    except Exception as e:
        t3 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print("请求失败,请求时间是:{}".format(t3))
        print('失败原因:%s'%e)

我们可以从下图中看到,如果不加请求超时的话,时间就有点长了。

 

标签:-%,请求,---,timeout,time,print,requests,localtime
来源: https://blog.csdn.net/qq_45534015/article/details/113091224

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有