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

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

问题描述

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



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



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



有更好的方法吗?我可以做些什么改进,使错误传播更加简洁和优雅?



这是我当前正在返回错误的一个例子:

  def get_data()
data1,error = get_some_data()#函数未显示
如果data1为None:
return无,无法检索data1
data2,error = get_some_other_data()#函数未显示
如果data2为无:
返回无无法检索data2
return(data1,data2),无

@ app.route(/ api / method,methods = ['GET'])
def method():
data,error = get_data()
如果数据为None:
如果错误为None:
error =unknown error
return json.dumps({error错误}),500
return json.dumps({data:data}),200


解决方案

你可以使用 abort(http_code) 向客户端返回适当的http代码,或者只是引发非http异常。并使用 @ app.errorhandler() decorator为http错误和任意异常提供自定义处理程序。你也可以使用一个普通的try / except块来处理一个异常。 Python不是你可以使用例外。


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?).

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

解决方案

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天全站免登陆