使用Flask-RESTPlus时如何不接受String type字段 [英] How to accept None for String type field when using Flask-RESTPlus
问题描述
我刚刚开始使用flask-restplus进行开发,而且我不是母语人士
I am just starting develop with flask-restplus and I am not a native speaker,
但是我会尽力描述我的问题.
but I will try to describe my question as clear as I can.
I know there is a fields
module in flask that help us define and filter response data type,
例如字符串,整数,列表等.
such as String, Integer, List and so on.
使用字段模块时,是否有任何方式允许NULL/无?
以下是我的代码,该代码使用字段模块捕获值,
the following is my code that using field module to catch the value,
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,则将引发以下错误,
and if the data type of display_name
is not String, there would be the following error raised,
{
"errors": {
"team_groups.0.display_name": "123 is not of type 'string'"
},
"message": "Input payload validation failed"
}
输入display_name时我想要的是什么,我可以输入 bulls
或 None
what I want is when entering display_name, I can enter bulls
or None
It seems few of the reference data / questions can be found, and I only found one result related
我的问题,但最终转换为非null值来解决问题.
to my question, but eventually converting as non-null value to solve the issue.
如果我的问题的任何部分不清楚,
if there is any part of my question not much clear,
请让我知道,谢谢.
以下是我的开发环境:
flask-restplus 0.13.0
Python 3.7.4
邮递员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
Yes, you can create a child class and use it instead of default ones, which will accept None as well
class NullableString(fields.String):
__schema_type__ = ['string', 'null']
__schema_example__ = 'nullable string'
所以您的代码看起来像
{ "property": NullableString(attribute=value)}
此外,您还可以访问 github.com/noirbizarre/flask-restplus/issues/179
这篇关于使用Flask-RESTPlus时如何不接受String type字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!