- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我编写了一个提供 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
}
是否可以在模型旁边显示用户定义的错误消息?有替代方案吗?
最佳答案
不要在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
。
关于python - 我可以在 restplus 模型旁边显示用户定义的错误消息吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913273/
我正在尝试使用 unicorn 运行 Restplus Flask API,但我不断收到此错误: Application object must be callable. 我正在使用 sqlalche
使用 python flask_restplus什么是发布和获取方法的正确方法来获取和推送文件,例如xlsx 到服务器? marshaling需要为此使用吗? 引用:https://philsturg
有什么办法可以对Namespace进行排序吗?条目添加到 Api 之后? 我正在关注文档,流程(AFAIK)似乎是: a) 创建 API: api = Api(version="1.0",
如何使用 Flask restplus 设置路径变量的默认值? 例如,使用以下内容: @api.route('/calendars/coordinates///years/') class Daily
我用 flask-restplus 制作了 api 服务器. 在使用它时,我注意到它可能必须进行版本控制才能扩大规模。 所以引用文档,我发现命名空间和蓝图是可用的。 首先,像这样的文件结构。 /app
所以我在 Flask RestPlus 中有这个模型: NS = Namespace('parent') PARENT_MODEL = NS.model('parent', { 'parent
在 Flask-Restplus 中,我需要对一个属性值建模,该属性值可能是字符串列表或对象列表。 它可以是这样的: { 'my_attribute': [ 'value1'
我正在使用 python 3.4。 我创建了一个 enum 类型,如下所示: import enum class EnumGender(enum.Enum): blank = ' '
我编写了一个提供 API 的 Flask 应用程序。我正在使用 RESTplus 库。 我使用一个模型来格式化数据。如果请求成功,则将值插入模型并返回模型。但是,如果请求不成功,则返回模型并且所有值为
我正在尝试使用 Flask-Restplus 制作一个 api 并用 swagger 记录它。 这是我目前所拥有的,它工作正常,除了我不知道如何添加根路由。 from flask import Fla
我很好奇如何从 Flask-RESTPlus 中的 GET 方法获取查询参数。我没有设法在文档中找到示例。 我以前使用过纯 flask ,我的做法是从 flask 库中调用“request.args.
我在将装饰器应用于我的 Resource 时遇到问题. Api decorators参数被应用于每个资源函数或者我如何理解 decorators范围?我的装饰器只在启动时应用,而不是在每次函数调用时应
我正在使用 Flask Rest-plus 模型来验证 POST 有效负载,但是如果存在任何额外/未知字段,我希望模型出错。 正在使用的型号: interface_config = api.model
我正在使用python flask创建REST API。 API已准备就绪,并且可以在我的本地主机的端口号8000上使用。现在,我打算为该REST API提供一个用户友好的界面,为此我决定使用pyth
我正在尝试从Flask-RESTplus获得Swagger UI,并在使用Nginx作为代理的服务器上工作。 Swagger在/ api上提供服务,并使用http://localhost:5000/a
目前命名空间解析器验证请求参数并抛出错误 { "errors": { "file": "Missing required parameter in an uploaded fi
给定这个 Flask Restplus 应用程序: from flask import Blueprint, Flask from flask_restplus import Api, Resourc
我正在尝试使用 Flask-RESTPlus 0.10.1 创建一个自定义字段来验证我的 API 中的 POSTed JSON 下面是基本设置... from flask_restplus impor
除了能够使用 Swagger UI 自动为我们的 API 生成交互式文档之外,使用 Flask-RESTplus 还有什么真正的优势吗?超过Flask-RESTful ? 最佳答案 我都使用过,我们切
我有一个 Flask REST API。我用healthcheck.EnvironmentDump以便轻松转储我的服务运行的环境。是否可以将端点添加到 Restplus 生成的 Swagger 文档中
我是一名优秀的程序员,十分优秀!