python接口自动化测试-requests请求异常处理

代码如下:

import json
import requests
from requests import exceptions
URL = 'https://api.github.com'
def build_uri(endpoint):
    return '/'.join([URL,endpoint])
def better_print(json_str):    #打印出来更好看
    return json.dumps(json.loads(json_str),indent=4)   #缩进为4def timeout_request():
    try:
        response = requests.get(build_uri('user/emails'),timeout=10)
        response.raise_for_status()   #状态不是200会抛异常
    except exceptions.Timeout as e:    #超时异常
        print(e)
    except exceptions.HTTPError as e:
        print(e)
    else:
        print(better_print(response.text))    #没问题时打印出来response内容
        print(response.status_code)
if __name__ == '__main__':
    timeout_request()

posted @ 2020-03-21 21:07  忆梦,惊梦  阅读(1358)  评论(0编辑  收藏  举报