python使用required定义必填字段

2025-12-01 0 11,572

说明

1、要想定义必填字段,只需要在 fields 里面加入 required 参数并设置为 True 即可。

2、还可以自定义错误信息,使用 error_messages 即可。

实例

from pprint import pprint
from marshmallow import Schema, fields, ValidationError
 
class UserSchema(Schema):
    name = fields.String(required=True)
    age = fields.Integer(required=True, error_messages={'required': 'Age is required.'})
    city = fields.String(
        required=True,
        error_messages={'required': {'message': 'City required', 'code': 400}},
    )
    email = fields.Email()
 
try:
    result = UserSchema().load({'email': 'foo@bar.com'})
except ValidationError as err:
    pprint(err.messages)

以上就是python使用required定义必填字段,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python使用required定义必填字段 https://www.zhiup.top/1464.html

相关