는 아래처럼 (하지만 간단한 사전 또는 데이터 구조를 수 형식) :
class User:
def __init__(self, first_name: str, last_name: str, date_of_birth: datetime, sex: str):
self.first_name = first_name
self.last_name = last_name
self.date_of_birth = date_of_birth
self.sex = sex
우리는 get_rules() 메소드 를 구현하여 우리는 우리가 하나 이상의 적절한 규칙 (들)을 제공해야 유효성을 검사 할 각 필드에 대해, 발리를 정의해야합니다. 경우에만 실행됩니다와 코드 내부이 경우
with UserValidator(user):
# do whatever you want with your valid model
: 상황에 맞는 프로세서로
:
from pyvaru import Validator
from pyvaru.rules import TypeRule, FullStringRule, ChoiceRule, PastDateRule
class UserValidator(Validator):
def get_rules(self) -> list:
user = self.data # type: User
return [
TypeRule(apply_to=user,
label='User',
valid_type=User,
error_message='User must be an instance of user model.',
stop_if_invalid=True),
FullStringRule(user.first_name, 'First name'),
FullStringRule(user.last_name, 'Last name'),
ChoiceRule(user.sex, 'Sex', choices=('M', 'F')),
PastDateRule(user.date_of_birth, 'Date of birth')
]
마지막으로 우리는 우리의 사용자 정의 유효성 검사기를 사용하는 방법에 대한 두 가지 선택이 유효성 검사가 성공하면 ValidationException (적절한 보고서와 함께 validation_result 속성 포함)이 발생합니다. 검증과를 실행하여
user = User(first_name=' ',
last_name=None,
date_of_birth=datetime(2020, 1, 1),
sex='unknown')
: 우리는 아래와 같이 구성된 사용자의 인스턴스가 가정의 (a에 ValidationResult을 반환) 유효성 검사() 메소드
validation = UserValidator(user).validate()
if validation.is_successful():
# do whatever you want with your valid model
else:
# you can take a proper action and access validation.errors
# in order to provide a useful message to the application user,
# write logs or whatever
를 호출하여
이전에 정의 된 규칙은 ValidationResult를 다음 오류와 함께 얻습니다.
{
'First name': ['String is empty.'],
'Last name': ['Not a string.'],
'Sex': ['Value not found in available choices.'],
'Date of birth': ['Not a past date.']
}
저는이 사실에 익숙하지 않지만 ORM (http://stackoverflow.com/questions/2781682/mongodb-orm-for-python 참조)을 사용하고자 할 것입니다. NoSQL DB의 유연성. –
감사합니다. 나는 ORM을 사용할 가능성을 알고 있지만이 경우에는 MongoDB 데이터베이스를 직접 조작하려고합니다. – anujkk
https://github.com/nicolaiarocci/cerberus/. 나는 관능적 인 것을 좋아하지만 지금은 케르 베루스를 선호합니다. 누구나 볼 수있는 yaml 파일에서 모든 규칙을 선언 할 수 있습니다. – chishaku