Flask restful使用嵌套字段生成具有嵌套响应的文档,得到TypeError:nested类型的对象不可JSON



我正在使用flask restx/flask restplus,试图利用swagger文档生成功能。我的模型有这个设置。

A = api.model(
'A', {
"a1": fields.String(description=''),
"a2": fields.String(description='')
}
)
B = api.model(
'B', {
"b1": fields.String(description=''),
"b2": fields.String(description='')
},
)
response_with_nested_data = api.model(
"TLD", {
"A": fields.Nested(
A, description=''
),
"B": fields.Nested(
B, description=''
)
}
)

我有一个看起来像的处理程序

@myapi.route('/aa', methods=['POST'])
class AA(Resource):
@myapi.expect(simple_expected_model)
@myapi.response(200, response_with_nested_data)
@do_auth(require_token=True, render_errors=True)
def post(self):
return handle_request(request)

我正试图从这个api端点获得输出,在swagger文档中,它看起来像

{
"A": {
"a1": "a",
"a2": "aa"
}
"B": {
"b1": "b",
"b2": "bb"
}
}

但当我启动服务器并点击我的swagger文档生成页面时,我得到了一个错误

TypeError: Object of type Nested is not JSON serializable

所以我知道我在这里做错了什么。有什么想法吗?我哪里错了,我应该怎么做?

我最终通过在decorator中使用关键字修复了这个问题。

@myapi.response(200, response_with_nested_data)

成为

@myapi.response(code=200, model=response_with_nested_data, description='')

相关内容

最新更新