zoukankan      html  css  js  c++  java
  • Python+request 获取响应(elapsed)和响应时间(timeout)《七》

    requests发请求时,接口的响应时间,也是我们需要关注的一个点,如果响应时间太长,也是不合理的。
    如果服务端没及时响应,也不能一直等着,可以设置一个timeout超时的时间

    具体的实现如下:

      超时(默认单位:s):

            timeout=0.5:设置到不大于0.5s的超时时间

                timeout=(0.5,0.8):设置区间时间的等待

        当出现超时时,则会抛出此异常:requests.exceptions.ConnectTimeout: HTTPConnectionPool    

      获取响应时间:

          r.elapsed.total_seconds()  

           

    #-*- coding:utf-8 -*-
    import requests
    from requests import exceptions
    
    try:
        #timeout=0.1 ,timeout=(0.5,0.8)
        r = requests.post(url=url, data=data, headers=headers, verify=False, timeout=0.5)

       r.elapsed.total_seconds() #获取实际的响应时间
       print r.json()
    except exceptions.Timeout as e: 

      print("抛出异常")

     

    进阶:

         如需要统一所有的测试接口的超时时间都可设置一致的话,那么只需要将timeout添加到配置文件中,统一进行管控即可,在测试的接口中timeout直接给定参数,那么在后期的更改timeout的超时时间,只在配置文件中更改即可。如果timeout的超时时间不需要那么的统一,则只需在每个请求的接口中写即可。

    示例:

    (1)在   host_header.yaml  的配置文件中添加timeout

    ########################## 测试环境,通用的headers配置 ######################################
    #请求接口的url的域名
    host: https://testapp.goodiber.com/v2/   #dev1的测试环境域名
    
    
    #请求接口的请求头中的共用参数
    headers:
      "version": "2.3.0"
      "version-id": "238"
      "os": "ios"
      "sign": "123456"
      "is-test": "1"
    
    #设置的超时时间
    timeout: 10

    (2)在使用的py文件,login.py 文件中调用即可。

    import yaml
    import sys,os
    import json
    
    
    # 导入yaml中的host
    reload(sys)
    sys.setdefaultencoding("utf-8")
    
    root_path = os.getcwd()[:-5]
    with open(root_path + "/Config/host_header.yaml", 'rb') as f:
        data = yaml.load(f)
    host = data["host"]
    timeout = data["timeout"]
    
    .....前面的url、headers的编写此处省略
    
    r = requests.post(url=url, data=data, headers=headers, verify=False,timeout = timeout)   #直接给定timeout参数即可
    get_reponse = r.json() # 获取到reponse返回的所有内容
     result = json.dumps(get_reponse, encoding="utf-8", ensure_ascii=False)   #将获取到的reponse中的中文已utf-8的格式显示。否则显示Unicode
  • 相关阅读:
    November 13th 2016 Week 47th Sunday The 1st Day
    November 12th 2016 Week 46th Saturday
    November 11th 2016 Week 46th Friday
    November 10th 2016 Week 46th Thursday
    November 9th 2016 Week 46th Wednesday
    November 8th 2016 Week 46th Tuesday
    windows 7文件共享方法
    Win7无线网络共享设置方法
    常量指针和指针常量
    如何查找局域网的外网ip
  • 原文地址:https://www.cnblogs.com/syw20170419/p/10951237.html
Copyright © 2011-2022 走看看