如何从requests.exceptions.RequestException获取异常字符串

问题描述 投票:2回答:1

我有以下烧瓶代码:

from flask import Flask,request,jsonify
import requests
from werkzeug.exceptions import InternalServerError, NotFound
import sys
import json



app = Flask(__name__)
app.config['SECRET_KEY'] = "Secret!"

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        rv['status_code'] = self.status_code
        return rv

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/test',methods=["GET","POST"])
def test():
    url = "https://httpbin.org/status/404"
    try:
        response = requests.get(url)
        if response.status_code != 200:
            try:
                response.raise_for_status()
            except requests.exceptions.HTTPError:
                status = response.status_code
                print status
                raise InvalidUsage("An HTTP exception has been raised",status_code=status)
    except requests.exceptions.RequestException as e:
        print e

if __name__ == "__main__":
    app.run(debug=True)

我的问题是如何从requests.exceptions.RequestException对象e中获取异常字符串(消息)和其他相关参数?

还有什么是记录此类异常的最佳方法。在HTTPError异常的情况下,我有要引用的状态代码。

但是requests.exceptions.RequestException捕获所有请求异常。那么我如何区分它们以及将它们与使用print语句区分开来的最佳方法是什么。

非常感谢您的任何答案。

python flask python-requests
1个回答
1
投票

RequestExceptionHTTPErrorConnectionErrorTimeoutURLRequiredTooManyRedirects等基类(整个列表可在GitHub page的请求模块中找到)。似乎处理每个错误并打印相应信息的最佳方法是从更具体的处理开始处理它们,并使用最常见的一个(基类)完成处理。这个在StackOverflow topic的评论中得到了广泛的阐述。对于你的test()方法,这可能是:

@app.route('/test',methods=["GET","POST"])
def test():
    url = "https://httpbin.org/status/404"
    try:
        # some code...
    except requests.exceptions.ConnectionError as ece:
        print("Connection Error:", ece)
    except requests.exceptions.Timeout as et:
        print("Timeout Error:", et)
    except requests.exceptions.RequestException as e:
        print("Some Ambiguous Exception:", e)

这样,您可以首先捕获从RequestException类继承的错误,哪些更具体。

并考虑打印语句的替代方案 - 我不确定这是否与您的意思完全相同,但您可以使用标准Python logging in Flasklogging module本身(此处为Python 3)登录控制台或文件。

© www.soinside.com 2019 - 2024. All rights reserved.