人生苦短_我用Python_Try_Exception异常捕捉_007

# coding=utf-8

'''
request+try__异常处理
'''
import requests


class HttpRequests:
    def __init__(self, url, payload=None):
        self.url = url
        self.payload = payload

    def get_or_post(self, method):
        try:  # try里面写的是要监控的code
            if method.upper() == 'GET':
                r = requests.get(self.url)
                res_get = r.text
                return res_get
            elif method.upper() == 'POST':
                self.payload = {'user': 'admin', 'pwd': '123456'}
                r = requests.post(self.url, data=self.payload)
                res_post = r.text
                return res_post
            else:
                return '请求的方式不存在......'
        except Exception as e:  # 捕捉异常
            print('请求失败,出现的错误是%s ' % e)
            # 错误抓起来,然后代码可以继续执行
            # try..Exception把异常信息获取到,并且对异常进行处理
            raise e  # 把异常抛出,因为异常捕捉到,还要将这个异常跑出来,不抛的话程序将异常视为正常,程序继续运行!


if __name__ == '__main__':
    http_res = HttpRequests('http://www.baidu.com')
    print(http_res.get_or_post(1))

 

posted @ 2018-06-07 22:26  Admin_sys  阅读(390)  评论(0编辑  收藏  举报