我正在尝试使用Flask-RESTPlus0.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+')),但这并没有给我提供自定义错误消息的控件,我希望它在哪里返回字段不是电子邮件类型。
我还添加了一个自定义validate_payload函数(在http://aviaryan.in/blog/gsoc/restplus-validation-custom-fields.html中找到),我在POST方法(而不是api.expect)中再次调用该函数。这需要我复制一些核心功能并每次调用它,除了api.expect之外,还需要输出适当的Swagger文档,并使用一些技巧使其在嵌套字段中工作。
我的理解是这应该是开箱即用的?我说错了吗?这里我漏掉了什么?
发布于 2018-11-01 23:09:32
我知道这有点老了,但也有同样的问题。
看起来"validate“实际上位于python jsonschema impl之上,如果您还对挖掘感兴趣,可以使用here
此外,您可以配置restplus API以使用更好的格式检查器,如下所示:(我还验证了date-time和date)
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
)https://stackoverflow.com/questions/48893302
复制相似问题