Python 使用Flask RESTPlus时如何接受字符串类型字段为None
我刚开始学习flask restplus,我不是母语人士 但我会尽可能清楚地描述我的问题 我知道有一个Python 使用Flask RESTPlus时如何接受字符串类型字段为None,python,flask,flask-sqlalchemy,flask-restplus,Python,Flask,Flask Sqlalchemy,Flask Restplus,我刚开始学习flask restplus,我不是母语人士 但我会尽可能清楚地描述我的问题 我知道有一个字段模块帮助我们定义和过滤响应数据类型 例如字符串、整数、列表等 使用字段模块时,是否有任何方法允许NULL/None? 下面是我使用field模块捕捉值的代码 add_group = api.model( "add_group", {"team_groups": fields.List(fields.Nested(api.model("team_groups",
字段
模块帮助我们定义和过滤响应数据类型
例如字符串、整数、列表等
使用字段模块时,是否有任何方法允许NULL/None?
下面是我使用field模块捕捉值的代码
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\u name
的数据类型不是String,则会出现以下错误:
{
"errors": {
"team_groups.0.display_name": "123 is not of type 'string'"
},
"message": "Input payload validation failed"
}
我想要的是在输入display\u name时,我可以输入bulls
或None
似乎可以找到的参考数据/问题很少,我只发现相关的 对于我的问题,但最终转换为非空值来解决这个问题 如果我的问题有不太清楚的地方 请让我知道,谢谢 以下是我的开发环境:
0.13.0
Python 3.7.4
postman 7.18.1
以下是我的更新代码:
{
"errors": {
"team_groups.0.display_name": "None is not of type 'string'"
},
"message": "Input payload validation failed"
}
来自flask\u restplus导入命名空间,字段
类NullableString(fields.String):
__模式\类型\类型=['string','null']
__schema_示例_uu='nullable string'
将设备分组到:
api=名称空间(“设备/组”,description=“设备组”)
header=api.parser().add_参数(“Authorization”,location=“headers”,help=“Bearer”)
获取详细信息组=api.model(
“获取详细信息”,
{“team_groups”:fields.List(fields.String)(必需=True,
description=“获取详细信息的团队组id”,示例=1))})
add_group=api.model(
“添加组”,
{“团队组”:fields.List(fields.Nested(api.model)(“团队组”){
“name”:fields.String(例如=“芝加哥公牛”,description=“添加组的名称”),
“显示名称”:NullableString(attribute='a')})
如果我输入以下有效载荷:(邮递员)
它仍然返回:
{
"errors": {
"team_groups.0.display_name": "None is not of type 'string'"
},
"message": "Input payload validation failed"
}
如果某些字段是可选的,则使required=False
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", required=False)})))})
是的,您可以创建一个子类并使用它来代替默认类,默认类也不接受
class NullableString(fields.String):
__schema_type__ = ['string', 'null']
__schema_example__ = 'nullable string'
所以你的代码看起来像
{ "property": NullableString(attribute=value)}
此外,您还可以访问该问题感谢您的友好回复,但尝试此操作后,仍会出现类似错误,如“team\u groups.0.display\u name”:“123不是'string'类型”
字段模块似乎仍不允许null通过感谢您的建议,我认为从字段.String
创建子类是一个好的方向,但我仍然不能将null传递给NullableString类,根据我更新的代码(在我的帖子上),我是否没有抓住要点?我认为你做得正确,应该可以正常工作,我将它与flask_restplus=0.12.1一起使用,这是我们必须使用的方法。更新为flask resplus==0.13.0
,然后使用@Stefan Answer。它会像符咒一样奏效。