首页 > 解决方案 > 使用 Flask-RESTPlus 时如何接受无字符串类型字段

问题描述


我刚开始使用 flask-restplus 进行开发,而且我不是母语人士,

但我会尽可能清楚地描述我的问题。

我知道烧瓶中fields有一个模块可以帮助我们定义和过滤响应数据类型,

如String、Integer、List等。

使用字段模块时有什么方法可以允许 NULL / None 吗?

以下是我使用字段模块捕获值的代码,

add_group = api.model(
        "add_group",
        {"team_groups": fields.List(fields.Nested(api.model("team_groups", {
            "name": fields.String(example="chicago bulls", description="name of add group"),
            "display_name": fields.String(example="bulls", description="display name of add group")})))})

如果数据类型display_name不是String,则会出现以下错误,

{
    "errors": {
        "team_groups.0.display_name": "123 is not of type 'string'"
    },
    "message": "Input payload validation failed"
}

我想要的是在输入 display_name 时,我可以输入bullsNone


似乎很少能找到参考数据/问题,我只找到了一个相关的结果

我的问题,但最终转换为非空值来解决问题。

如果我的问题的任何部分不太清楚,

请告诉我,谢谢。

以下是我的开发环境:

flask-restplus 0.13.0 Python 3.7.4 postman 7.18.1


以下是我更新的代码:

from flask_restplus import Namespace, fields

class NullableString(fields.String):
    __schema_type__ = ['string', 'null']
    __schema_example__ = 'nullable string'

class DeviceGroupDto:
    api = Namespace("device/group", description="device groups")
    header = api.parser().add_argument("Authorization", location="headers", help="Bearer ")

    get_detail_group = api.model(
        "getdetail",
        {"team_groups": fields.List(fields.String(required=True,
                                                  description="team group id to get detail", example=1))})

    add_group = api.model(
        "add_group",
        {"team_groups": fields.List(fields.Nested(api.model("team_groups", {
            "name": fields.String(example="chicago bulls", description="name of add group"),
            "display_name": NullableString(attribute='a')})))})

如果我输入以下有效载荷:(邮递员)

{
    "team_groups": [
        {
            "name": "chicago bulls",
            "display_name": null
        }
    ]
}

它仍然返回:

{
    "errors": {
        "team_groups.0.display_name": "None is not of type 'string'"
    },
    "message": "Input payload validation failed"
}

标签: pythonflaskflask-sqlalchemyflask-restplus

解决方案


是的,您可以创建一个子类并使用它来代替默认的,这也将接受 None

class NullableString(fields.String):
    __schema_type__ = ['string', 'null']
    __schema_example__ = 'nullable string'

所以你的代码看起来像

{ "property": NullableString(attribute=value)}

此外,您可以访问问题github.com/noirbizarre/flask-restplus/issues/179


推荐阅读