繁体   English   中英

允许在 flask-restx / flask-restplus 中的字段中使用空值

[英]Allow null values in a field in flask-restx / flask-restplus

我正在使用 flask-restx 来构建 API。

我的 api 模型如下所示:

myModel = api.model(
    'myModel', 
    {
        'id' : fields.Integer(min=1, required=True),
        'code' : fields.String(enum=["A", "B", "C"], required=False),
    }
)

通过这样做,代码不能为空。

但有时,代码字段为空。 如果不是,则它必须是ABC值之一。

我无法将None添加到枚举列表中,因为它不是字符串。

如何使其成为 null ?

在你的脚本中添加

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

然后

myModel = api.model(
    'myModel', 
    {
        'id' : fields.Integer(min=1, required=True),
        'code' : NullableString(enum=["A", "B", "C"], required=False),
    }
)

这应该允许您的字段为空

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM