Webargs字段非空验证:使用validate参数
from\ marshmallow\ import\ Schema,\ ValidationError,\ validate\nfrom\ webargs\ import\ fields\n\ndef\ non_empty_string(value):\n if\ not\ value:\n raise\ ValidationError('字段值不能为空')\n\nclass\ MySchema(Schema):\n main_text\ =\ fields.Str(description='主题文字',\ required=True,\ validate=non_empty_string)\n\n\n#\ 使用示例\n\ndata\ =\ {'main_text': ''} \n\ntry:\n result\ =\ MySchema().load(data)\nexcept\ ValidationError\ as\ err:\n print(err.messages) #\ 输出:\ {'main_text': ['字段值不能为空']}\n
原文地址: https://www.cveoy.top/t/topic/p6Dt 著作权归作者所有。请勿转载和采集!