我刚刚开始使用 Flask-restplus 进行开发,我不是母语人士,
但我会尽力尽可能清楚地描述我的问题。
我知道有一个fields
模块输入flask https://flask-restplus.readthedocs.io/en/0.8.3/fields.html帮助我们定义和过滤响应数据类型,
如字符串、整数、列表等。
使用 fields 模块时有什么办法允许 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时,我可以输入bulls
or None
貌似参考资料/问题很少能找到,我只找到了一个结果 https://stackoverflow.com/questions/56840335/how-to-accept-none-for-integer-type-field related
对于我的问题,但最终转换为非空值来解决问题。
如果我的问题有任何部分不太清楚,
请告诉我,谢谢。
以下是我的开发环境:
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"
}