要对字段做非空验证,可以使用webargs库中的validate参数。你可以使用validate参数来指定一个验证函数,该函数将在字段验证时被调用。在验证函数中,你可以检查字段的值是否为非空。

以下是一个示例,演示如何使用validate参数进行非空验证:

from marshmallow import Schema, ValidationError, validate
from webargs import fields

def non_empty_string(value):
    if not value:
        raise ValidationError('字段值不能为空')

class MySchema(Schema):
    main_text = fields.Str(description='主题文字', required=True, validate=non_empty_string)

在上面的示例中,我们定义了一个验证函数non_empty_string,它检查字段的值是否为空。如果为空,我们抛出一个ValidationError异常,其中包含自定义的错误消息。

然后,我们在MySchema中的main_text字段上使用validate参数来指定验证函数。这样,当对main_text字段进行验证时,将调用non_empty_string函数进行非空验证。

如果字段的值为空,则会引发ValidationError异常,并且可以在异常对象的messages属性中获取错误消息。

使用示例:

data = {'main_text': ''}
try:
    result = MySchema().load(data)
except ValidationError as err:
    print(err.messages)  # 输出: {'main_text': ['字段值不能为空']}

请注意,在上面的示例中,MySchema().load(data)将抛出ValidationError异常,因为main_text字段的值为空

from marshmallow import Schema from webargs import fields main_text = fieldsStrdescription=主题文字 required=True 对字段做非空验证怎么修改

原文地址: https://www.cveoy.top/t/topic/ioMq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录