带有List字段的Flask-Restful-Swagger Model类

时间:2016-03-31 19:15:13

标签: python swagger flask-restful

我目前正在使用tlEditor.Nodes.Add(TempItem1.ToArray) 构建API的文档。我的一个资源返回一个带有一个元素的dict:一个数组。数组中的项目的格式为

Flask-Restful-Swagger

等等。字段是bool,str,int或float。阵列的每个元素中总共有32个字段。我正在尝试构建{ "active": bool, "affectation": str, "alert_type": str, ... } 类以用作@swagger.model

首先我尝试了:

responseClass

在Swagger的HTML视图中产生了预期的输出:

@swagger.model
class ReportListGet:
    resource_fields = {
        'items': fields.List(fields.String)
    }

所以我尝试在它之上构建以显示实际的响应。类似的东西:

{
  "items": [
    ""
  ]
}

我的第二次尝试是创建一个包含所有字段的字典,然后使用fields.Nested like:

{
  "items": [
    {
       "active": fields.Boolean,
       "affectation": fields.String,
       "alert_type": fields.String, ...
    }
  ]
}

但HTML中的输出是

resource_fields = {
    'items': fields.List(fields.Nested(report_fields))
}

然后我尝试创建自己继承自{ "items": [ null ] } 的字段,但它在HTML上给了我相同的fields.Raw字典。为字段分配默认值也不起作用。

1 个答案:

答案 0 :(得分:1)

我明白了!

主要课程最终如下:

@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's GitHub page的示例中找到了我需要的线索。有用的代码从第157行开始。

现在,Swagger的HTML视图显示了这一点:

{
  "items": [
    {
      "active": "",
      "affectation": "",
      "alert_type": "",
      ...
    }
  ]
}