首页 文章

使用Flask-RESTPlus验证自定义字段

提问于
浏览
2

我正在尝试创建一个自定义字段,用于使用Flask-RESTPlus 0.10.1在我的API中验证POSTed 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+')) ,但这并不是't give me the control to customize the error message, where' d我希望它返回该字段不是电子邮件类型 .

我还继续添加了一个自定义 validate_payload 函数(在http://aviaryan.in/blog/gsoc/restplus-validation-custom-fields.html中找到),我在POST方法中再次调用(而不是 api.expect ) . 这需要我复制一些核心功能,并且每次除了 api.expect 之外都要调用它来输出正确的Swagger文档和一些技巧以使其在嵌套字段中工作 .

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

1 回答

  • 1

    我很欣赏这有点旧,但也有同样的问题 .

    它看起来像"validate"实际上坐在一个python jsonschema impl,如果你're still interested in digging, it' s可用here

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

    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
    )
    

相关问题