我目前正在使用Flask-Restful-Swagger
为API构建文档。我的一个资源返回了一个dict,其中有一个元素:数组。阵列中的项目的形式为
{
"active": bool,
"affectation": str,
"alert_type": str, ...
}
等等。字段为bool、str、int或float。在数组的每个元素中总共有32个字段。我正在尝试构建@swagger.model
类以用作responseClass
。
我第一次尝试:
@swagger.model
class ReportListGet:
resource_fields = {
'items': fields.List(fields.String)
}
它在Swagger:的HTML视图上产生了预期的输出
{
"items": [
""
]
}
因此,我试图在此基础上进行构建,以显示实际的响应。类似于:
{
"items": [
{
"active": fields.Boolean,
"affectation": fields.String,
"alert_type": fields.String, ...
}
]
}
我的第二次尝试是创建一个包含所有字段的字典,然后使用字段。嵌套式:
resource_fields = {
'items': fields.List(fields.Nested(report_fields))
}
但是HTML中的输出是
{
"items": [
null
]
}
然后,我尝试创建自己的继承自fields.Raw
的字段,但它在HTML上给了我相同的null
dict。为字段指定默认值也不起作用。
我想通了!
主要课程的结局是这样的:
@swagger.model
@swagger.nested(
items=Report.__name__)
class ReportListGet:
resource_fields = {
'items': fields.List(fields.Nested(Report.resource_fields))
}
另一个类只是一个常规的@swagger.model
:
@swagger.model
class Report:
resource_fields = {
"active": fields.String,
"affectation": fields.String,
"alert_type": fields.String,
...
}
从Restful Flask Swagger的GitHub页面的例子中找到了我需要的线索。有用的代码从第157行开始。
现在Swagger的HTML视图显示如下:
{
"items": [
{
"active": "",
"affectation": "",
"alert_type": "",
...
}
]
}