【问题标题】:Can I have a user-defined error message next to a restplus model?我可以在 restplus 模型旁边显示用户定义的错误消息吗?
【发布时间】:2019-11-18 11:12:28
【问题描述】:

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

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

这是一个最小的例子:

from flask import Flask
from flask_restplus import Resource, fields, Api


app = Flask(__name__)

api = Api()
api.init_app(app)


books = {'1': {"id": 1, "title": "Learning JavaScript Design Patterns", 'author': "Addy Osmani"},
         '2': {"id": 2, "title": "Speaking JavaScript", "author": "Axel Rauschmayer"}}

book_model = api.model('Book', {
    'id': fields.String(),
    'title': fields.String(),
    'author': fields.String(),
})

@api.route('/books/<id>')
class ApiBook(Resource):

    @api.marshal_with(book_model)
    def get(self, id):
        try:
            return books[id]
        except KeyError as e:
            return {'message': 'Id does not exist'}

if __name__ == '__main__':
    app.run()

成功输出

curl -X GET "http://127.0.0.1:5000/books/1" -H "accept: application/json"

{
  "id": "1",
  "title": "Learning JavaScript Design Patterns",
  "author": "Addy Osmani"
}

错误输出

curl -X GET "http://127.0.0.1:5000/books/3" -H "accept: application/json"

{
  "id": null,
  "title": null,
  "author": null
}

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

【问题讨论】:

    标签: python python-3.x flask flask-restplus


    【解决方案1】:

    不要在get方法中捕获异常然后返回一个对象;您从该方法返回的任何内容都将使用模型进行编组。

    改为遵循error handling documentation 并使用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 does not exist"}

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

    @api.errorhandler(KeyError)
    def handle_keyerror(error):
        return {"message": f"Object with id {error} could not be found"}, 404
    

    然后不要在get() 方法中捕获异常

    @api.marshal_with(book_model)
    def get(self, id):
        return books[id]
    

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

    curl -X GET "http://127.0.0.1:5000/books/3" -H "accept: application/json"
    {
        "message": "Object with id '3' could not be found. You have requested this URI [/books/3] but did you mean /books/<id> ?"
    }
    

    这可能对您的具体情况没有太大帮助,因此您可能需要禁用 ERROR_404_HELP

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-26
      • 2012-01-30
      • 1970-01-01
      • 2012-06-12
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多