python-3.x 棉花糖自定义“验证器”功能不工作

bq9c1y66  于 2023-03-31  发布在  Python
关注(0)|答案(1)|浏览(95)

我创建棉花糖自定义字段如下:

from marshmallow.fields import Field

class CustomFiled(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        pass

    def _deserialize(self, value, attr, data, **kwargs):
        pass

然后创建custom validator,如下所示:

from marshmallow import ValidationError

def customValidation(value):
    # why value is None, not "some value here" ??
    print("value:", value)

    if value is None:
        raise ValidationError("custom_field cannot be None!")

和开始验证的主代码:

from marshmallow import ValidationError, Schema

def main():
    try:
        data = {
            "custom_field": "some value here"
        }
        schema = {
            "custom_field": CustomFiled(required=True, validate=customValidation)
        }

        # validation begin
        ma_schema = Schema.from_dict(schema)
        ma_schema().load(data)

        # if no error occurs, then validation success
        print("Validation Success! :)")
    except ValidationError as e:
        print(e.messages)

'''
output on terminal:
    value: None
    {'custom_field': ['custom_field cannot be None!']}
'''
main()

这是完整的源代码:

from marshmallow.fields import Field
from marshmallow import ValidationError, Schema

class CustomFiled(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        pass

    def _deserialize(self, value, attr, data, **kwargs):
        pass

def customValidation(value):
    # why value is None, not "some value here" ??
    print("value:", value)

    if value is None:
        raise ValidationError("custom_field cannot be None!")

def main():
    try:
        data = {
            "custom_field": "some value here"
        }
        schema = {
            "custom_field": CustomFiled(required=True, validate=customValidation)
        }

        # validation begin
        ma_schema = Schema.from_dict(schema)
        ma_schema().load(data)

        # if no error occurs, then validation success
        print("Validation Success! :)")
    except ValidationError as e:
        print(e.messages)

'''
output on terminal:
    value: None
    {'custom_field': ['custom_field cannot be None!']}
'''
main()

为什么函数customValidation()上的arg valueNone而不是"some value here"
我想终端的输出:
“value:这里有一些值”
“验证成功!:)”
但是当我尝试使用内置验证器(Str). arg value on customValidator(value)时,会打印出来。下面是代码:

from marshmallow.fields import Str
from marshmallow import ValidationError, Schema

def supposed():
    def customValidator(value):
        print("value: ", value)

    try:
        data = {
            "name": "candra"
        }
        schema = {
            "name": Str(validate=customValidator)
        }

        # validation begin
        ma_schema = Schema.from_dict(schema)
        ma_schema().load(data)

        # if no error occurs, then validation success
        print("Validation Success! :)")
    except ValidationError as e:
        print(e.messages)

'''
Terminal output:
    value:  candra
    Validation Success! :)
'''
supposed()

端子上的输出:
值:坎德拉
验证成功!:)
这里,candra取自schema = { "name": Str(validate=customValidator) }经过的data = {'name': 'candra'}

iecba09b

iecba09b1#

我终于意识到什么是错误的,覆盖方法_deserialize()是无效的(返回None),它应该返回值传递给customValidation()
这里的代码:

class CustomFiled(Field):
    def _deserialize(self, value, attr, data, **kwargs):
        return value

def main():
    def customValidation(value):
        print("value:", value)

    try:
        data = {
            "custom_field": "some value here"
        }
        schema = {
            "custom_field": CustomFiled(required=True, validate=customValidation)
        }

        # validation begin
        ma_schema = Schema.from_dict(schema)
        ma_schema().load(data)

        # if no error occurs, then validation success
        print("Validation Success! :)")
    except ValidationError as e:
        print(e.messages)

main()

输出为:
“value:这里有一些值”
“验证成功!:)”
我是多么愚蠢😅

相关问题