首页 > 其他 > 详细

requests库之请求异常处理

时间:2017-08-13 19:05:20      阅读:981      评论:0      收藏:0      [点我收藏+]

利用requests发出请求时可能会发生异常,requests中有一个exception库用来区分这些异常。

http协议是基于tcp/ip协议的,tcp/ip三次握手,因此可以在请求中定义等待时间,超出等待时间仍未到达则请求失败。如requests.get(url,timeout=(3,7)),requests.get(url,timeout=10)

import json
import requests
from requests import exceptions

URL = https://api.github.com

#构建uri
def build_uri(endpoint):
    return /.join([URL,endpoint])

def timeout_request():
    try:
        response = requests.get(build_uri(user/emails),timeout=5)
        response.raise_for_status()
    except exceptions.Timeout as e:
        print(e)
    except exceptions.HTTPError as e:
        print(e)

if __name__==__main__:
    timeout_request()

 

requests库之请求异常处理

原文:http://www.cnblogs.com/HJhj/p/7354324.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!