【发布时间】: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