python - 使用 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 时,我可以输入bulls
或None
似乎很少能找到参考数据/问题,我只找到了一个相关的结果
我的问题,但最终转换为非空值来解决问题。
如果我的问题的任何部分不太清楚,
请告诉我,谢谢。
以下是我的开发环境:
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"
}
解决方案
是的,您可以创建一个子类并使用它来代替默认的,这也将接受 None
class NullableString(fields.String):
__schema_type__ = ['string', 'null']
__schema_example__ = 'nullable string'
所以你的代码看起来像
{ "property": NullableString(attribute=value)}
推荐阅读
- xaml - 如何从 Xamarin 表单中的 IOS Listview 中删除此箭头或图像
- android-studio - 保存矢量资产输出目录不正常
- linq - 与 EF Core 驱动程序 v2.2 连接
- flutter - Flutter 布局:未显示 VerticalDividers
- mysql - 如何聚合不同粒度级别的加权平均字段?
- swagger-ui - 如何在 swagger UI 中测试休息服务时将查询参数传递给 url
- angular - 如何根据其他单选按钮组值向单选按钮组显示和添加验证
- python - 从txt文件中查找关键字并复制目标文件
- docker - dockerd --max-concurrent-downloads 1 命令未找到
- python - 如何在 Activation('elu') 层中设置'alpha'参数