使用 Python 和 Flask 返回 API 错误消息 [英] Returning API Error Messages with Python and Flask

查看:51
本文介绍了使用 Python 和 Flask 返回 API 错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 和 Flask 设计一个 RESTful API.正如预期的那样,如果一切顺利,API 需要接收 API 请求并返回数据,但在发生错误的情况下,它需要软失败并返回正确的错误.我通常会在出现错误时引发异常,但在这种情况下,我需要将错误消息返回给用户(try-catch 块?).

I am designing a RESTful API using Python and Flask. As expected, the API needs to receive an API request and return data if all goes well, but in the instance of an error, it needs to fail softly and return the proper error. I typically raise exceptions when an error results, but in this case I need to return the error message to the user (try-catch block?).

我目前处理错误的方式是让我的函数返回数据和错误,并检查每个级别的数据,最后将数据或错误返回给 API 函数的调用者.

The way I am currently dealing with errors is to have my functions return both the data and an error, and to check for the data at each level, finally returning either the data or the error to the caller of the API function.

这样做的问题是,当有多个级别的函数调用时,它会变得很麻烦,需要我的函数多次传递数据和错误并每次都执行检查.

The problem with this is that it can get cumbersome when there are several levels of function calls, requiring my functions to pass data and errors several times and perform checks each time.

有没有更好的方法来做到这一点?我可以进行哪些改进以使错误传播更加简单和优雅?

Is there a better way to do this? What are some improvements I could make to make the error propagation more simple and elegant?

以下是我当前返回错误方式的示例:

Here is an example of the way I'm currently returning errors:

def get_data()
    data1, error = get_some_data() # function not shown
    if data1 is None:
         return None, "could not retrieve data1"
    data2, error = get_some_other_data() # function not shown
    if data2 is None:
         return None, "could not retrieve data2"
    return (data1, data2), None

@app.route("/api/method", methods=['GET'])
def method():
    data, error = get_data()
    if data is None:
        if error is None:
            error = "unknown error"
        return json.dumps({ "error": error }), 500
    return json.dumps({ "data": data }), 200

推荐答案

你可以使用 abort(http_code) 将适当的 http 代码返回给客户端,或者只是引发非 http 异常.并使用 @app.errorhandler() 装饰器为 http 错误和任意异常提供自定义处理程序.您还可以使用普通的 try/except 块来处理异常.Python 不是 Go,你可以使用异常.

You could use abort(http_code) to return an appropriate http code to the client or just raise a non-http exception. And use @app.errorhandler() decorator to provide a custom handler for http errors and arbitrary exceptions. You could also use an ordinary try/except block where you are ready to handle an exception. Python is not Go you can use exceptions.

这篇关于使用 Python 和 Flask 返回 API 错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆