Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách kiểm tra dữ liệu với Cerberus trong Python

Giới thiệu

Cerberus cung cấp validation nhẹ nhưng mạnh mẽ, có thể mở rộng cho custom validation. Định nghĩa schema → validate data → báo lỗi chính xác nếu không khớp. Có thể áp dụng nhiều điều kiện cùng lúc cho một field.

Cài đặt

pip install Cerberus
from cerberus import Validator

Validate dictionary

schema = {'numbers': {'type': 'integer'}}
v = Validator(schema)
data = {'numbers': 5}
if v.validate(data):
    print("Data is valid")
else:
    print("Data is invalid")
Data is valid

Validate với nhiều quy tắc và in lỗi

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)
Data is invalid, {'ID': ['required field']}

Đặt giới hạn min/max

from cerberus import Validator
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)
Data is invalid {'age': ['min value is 18'], 'name': ['min length is 5']}

Kết luận

Đã học validate dict/JSON/API data với schema tùy chỉnh. Có thể tự động hóa validation cho web động. Tránh lỗi khi build DB hoặc phân tích dữ liệu. Xem tài liệu.