程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python cerberus Validator參數校驗

編輯:Python

最簡單用法

# 最簡單用法
from cerberus import Validator
schema = {'name1': {'type': 'string'}, 'name2': {'type': 'string'}}
v = Validator(schema)
document = {'name1': 'john doe', 'name2': 0}
if v.validate(document):
print('data is valid')
else:
print(v.errors)

輸出:

{'name2': ['must be of string type']}

自定義校驗方法代碼示例: 

# coding=utf-8
from cerberus import Validator
class ParamValidator(Validator):
def __init__(self, *args, **kwargs):
self.res = {}
super(ParamValidator, self).__init__(*args, **kwargs)
def _validator_username(self, field, value):
print(" --- in _validator_username ---")
print("field = {}, value = {}".format(field, value))
name = value.get('username', None)
print("name = {}".format(name))
if not name:
return self._error('error_info', 'not username')
def _check_with_gender(self, field, value):
print("--- in _check_with_gender ---")
print("field = {} | value = {}".format(field, value))
self.res.update({"field": field, "value": value})
if __name__ == "__main__":
# No.1 自定義前綴為:_validator_<validator_name>的校驗方法
document = {'data': {'username': ''}}
# schema_rule中validator對應的值為username,會自動去找_validator前綴的_validator_username方法
schema_rule = {"data": {'validator': 'username'}}
pv = ParamValidator(schema_rule)
if not pv.validate(document):
print("pv.document = {}".format(pv.document))
print("pv.errors = {}".format(pv.errors))
else:
print("validator success end ---")
print('='*20 + '分割線' + '='*20)
# No.2 - 自定義前綴為_check_with<field>的校驗方法
document = {'name': "1", 'age': 3, 'gender': 'male-'}
# schema_rule中gender對應的值中check_with字段對應的值為gengder,會自動去找_check_with前綴的_check_with_gender方法執行
schema_rule = {
'name': {'type': 'string'},
'age': {'default': 18, 'type': 'integer'},
'gender': {'type': "string", "allowed": ["male", "female"], "check_with": "gender"}
}
pv = ParamValidator(schema_rule)
res = pv.validate(document)
print("res = {}".format(res))
print("pv.document = {}".format(pv.document))
print("pv.errors = {}".format(pv.errors))
print("pv.res = {}".format(pv.res))

輸出:

 --- in _validator_username ---
field = data, value = {'username': ''}
name =
pv.document = {'data': {'username': ''}}
pv.errors = {'error_info': ['not username']}
====================分割線====================
--- in _check_with_gender ---
field = gender | value = male-
res = False
pv.document = {'gender': 'male-', 'age': 3, 'name': '1'}
pv.errors = {'gender': ['unallowed value male-']}
pv.res = {'field': 'gender', 'value': 'male-'}


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved