บทนำ
Cerberus เป็น validation libraryน้ำหนักเบา ขยายได้ ใช้ schema-based validation สำหรับ dict, JSON, config files ฯลฯ
การติดตั้ง
pip install Cerberus
การใช้งานพื้นฐาน
1. กำหนด Schema และ Validate
from cerberus import Validator
schema = {'numbers': {'type': 'integer'}}
v = Validator(schema)
data = {'numbers': 5}
if v.validate(data):
print("Data is valid")
else:
print("Data is invalid")2. Validation หลายเงื่อนไข และ แสดง Errors
from cerberus import Validator
v = Validator()
v.schema = {'ID': {'required': True, 'type': 'number'},
'age': {'type': 'integer'}}
if v.validate({'age': 60}):
print('Data is valid')
else:
print('Data is invalid')
print(v.errors)
# Output: Data is invalid, {'ID': ['required field']}3. กำหนด Min/Max ค่า และ ความยาว String
v = Validator()
v.schema = {'name': {'type': 'string', 'minlength': 5},
'age': {'type': 'integer', 'min': 18, 'max': 65}}
if v.validate({'name': 'VJ', 'age': 16}):
print('Data is valid')
else:
print('Data is invalid')
print(v.errors)
# Output: Data is invalid {'age': ['min value is 18'], 'name': ['min length is 5']}คำอธิบาย
- Schema เป็น dict ที่กำหนด rules ต่อ field
- Rules พบบ่อย:
type,required,min,max,minlength,maxlength,allowed,regex,dependencies v.errorsคืนค่า dict ระบุ field ที่ fail และเหตุผล- รองรับ nested dict, list of dicts, custom validators
กรณีใช้งาน
- Validate API input ก่อนเข้า database
- Validate config files
- Data cleaning pipeline
- Automate validation ใน CI/CD