Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我可以在restplus模型旁边有一条用户定义的错误消息吗?_Python_Python 3.x_Flask_Flask Restplus - Fatal编程技术网

Python 我可以在restplus模型旁边有一条用户定义的错误消息吗?

Python 我可以在restplus模型旁边有一条用户定义的错误消息吗?,python,python-3.x,flask,flask-restplus,Python,Python 3.x,Flask,Flask Restplus,我已经编写了一个提供API的Flask应用程序。我正在使用RESTplus库 我使用模型来格式化数据。如果请求成功,则将值插入模型并返回模型。 但是,如果请求不成功,将返回模型,并且所有值均为null。我的目标是返回具有多个键值对的用户定义的错误消息。错误消息的结构应与as模型不同 下面是一个简单的例子: 从烧瓶导入烧瓶 从restplus导入资源、字段和Api app=烧瓶(名称) api=api() api.init_应用程序(应用程序) books={'1':{'id:1',title:“

我已经编写了一个提供API的
Flask
应用程序。我正在使用
RESTplus

我使用模型来格式化数据。如果请求成功,则将值插入模型并返回模型。 但是,如果请求不成功,将返回模型,并且所有值均为
null
。我的目标是返回具有多个键值对的用户定义的错误消息。错误消息的结构应与as模型不同

下面是一个简单的例子:

从烧瓶导入烧瓶
从restplus导入资源、字段和Api
app=烧瓶(名称)
api=api()
api.init_应用程序(应用程序)
books={'1':{'id:1',title:“学习JavaScript设计模式”,“author':“Addy Osmani”},
'2':{“id”:2,“title”:“说JavaScript”,“author”:“Axel Rauschmayer”}
book_model=api.model('book'{
“id”:字段。字符串(),
“标题”:字段。字符串(),
“作者”:字段。字符串(),
})
@api.route(“/books/”)
课程手册(资源):
@api.marshal_与(书本模型)
def get(自我,id):
尝试:
还书[id]
除KeyError外,如e:
返回{'message':'Id不存在'}
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run()
成功输出

curl-X GET”http://127.0.0.1:5000/books/1“-H”接受:应用程序/json“

输出错误

curl-X GET”http://127.0.0.1:5000/books/3“-H”接受:应用程序/json“


模型旁边是否可能有用户定义的错误消息?有其他选择吗?

不要在
get
方法中捕获异常,然后返回一个对象;从方法返回的任何内容都将使用模型进行封送处理

相反,请遵循并使用
flask.abort()
设置带有消息的
404
响应:

# at the top of your module
from flask import abort

# in the resource class
@api.marshal_with(book_model)
def get(self, id):
    try:
        return books[id]
    except KeyError as e:
        raise abort(404, 'Id does not exist')
您给出的第二个参数
abort()
自动转换为带有
message
键的JSON对象,因此
{“message”:“Id不存在”}

您还可以为
KeyError
异常创建
@api.errorhandler
注册,并将其转换为404响应:

@api.errorhandler(KeyError)
def handle_keyerror(error):
    return {"message": f"Object with id {error} could not be found"}, 404
然后不要在
get()
方法中捕获异常:

请注意,当
ERROR\u 404\u HELP
设置为
True
(默认值)时,RestPlus会将消息添加到另一个路由建议中,并附加到每个404响应中:

@api.errorhandler(KeyError)
def handle_keyerror(error):
    return {"message": f"Object with id {error} could not be found"}, 404
curl-X GET”http://127.0.0.1:5000/books/3-H“接受:应用程序/json”
{
“消息”:“找不到id为“3”的对象。您请求了此URI[/books/3],但您的意思是/books/?”
}
在您的特定情况下,这可能没有多大帮助,因此您可能需要禁用
ERROR\u 404\u HELP

@api.errorhandler(KeyError)
def handle_keyerror(error):
    return {"message": f"Object with id {error} could not be found"}, 404
@api.marshal_with(book_model)
def get(self, id):
    return books[id]