使用Flask RESTPlus验证自定义字段

使用Flask RESTPlus验证自定义字段,flask,flask-restplus,Flask,Flask Restplus,我正在尝试使用Flask RESTPlus 0.10.1创建一个自定义字段,用于验证API中发布的JSON 下面是基本设置 from flask_restplus import fields import re EMAIL_REGEX = re.compile(r'\S+@\S+\.\S+') class Email(fields.String): __schema_type__ = 'string' __schema_format__ = 'email' __sch

我正在尝试使用Flask RESTPlus 0.10.1创建一个自定义字段,用于验证API中发布的JSON

下面是基本设置

from flask_restplus import fields
import re

EMAIL_REGEX = re.compile(r'\S+@\S+\.\S+')

class Email(fields.String):
    __schema_type__ = 'string'
    __schema_format__ = 'email'
    __schema_example__ = 'email@domain.com'

    def validate(self, value):
        if not value:
            return False if self.required else True
        if not EMAIL_REGEX.match(value):
            return False
        return True
我喜欢上面的文档在Swagger UI中的方式,但我似乎不知道如何在上面实际使用validate方法

下面是我如何使用自定义字段

Json = api.model('Input JSON', {
    'subscribers': fields.List(Email),
    [...]
})


@api.expect(Json)    // validate is globally set to true
def post(self):
    pass
我很幸运使用了
'subscribers':fields.List(fields.String(pattern='\S+@\S+\.\S+'))
,但这并没有给我自定义错误消息的控件,我希望它返回该字段不是电子邮件类型

我还添加了一个自定义的
validate\u payload
函数(在中找到),我在POST方法中再次调用该函数(而不是
api.expect
)。这需要我复制一些核心功能,并在
api之外每次调用它。希望
能够输出正确的招摇过市文档,并通过一些技巧使其在嵌套字段中工作


我的理解是这应该是开箱即用的?我错了吗?我在这里遗漏了什么?

我很感激这有点陈旧,但也有同样的问题

看起来“验证”实际上位于python jsonschema impl之上,如果您仍然对挖掘感兴趣,那么它是可用的

除此之外,您可以配置restplus API以使用更好的formatchecker,如下所示:(我还验证日期时间和日期)


用一句话来说,你的问题到底是什么!您好@aesterisk,您是否了解如何使用
@api验证自定义字段。expect
format_checker = FormatChecker(formats=["date-time", "email", "date"])
api_v1 = Api(
    app, version='1.4',
    title='[Anon]',
    description='[Anon] API for developers',
    format_checker=format_checker
)