import copy import re class ValidateError(Exception): def __init__(self, detail): self.detail = detail # ###################### 插件 class TextInput(object): def __str__(self): return "<input type='text' />" class EmailInput(object): def __str__(self): return "<input type='email' />" # ###################### 内部包含正则,用于验证 class Fild(object): def __init__(self,required=True,error_message=None,widget=None): self.error_message=error_message self.widget=widget self.required=required def __str__(self): return str(self.widget) class CharFiled(Fild): def valid(self, val): if self.required: if not val: msg = self.error_message['required'] raise ValidateError(msg) return val class EmailFiled(Fild): REG = "^w+@w+$" def valid(self, val): if self.required: if not val: msg = self.error_message['required'] raise ValidateError(msg) result = re.match(self.REG, val) if not result: msg = self.error_message.get('invalid', '格式错误') raise ValidateError(msg) return val # ###################### Form,获取用户提交内容+获取定义的字段对象 class Form(object): def __init__(self,data): self.data=data self.clean_data={} self.errors={} self.fields=copy.deepcopy(self.__class__.declare_field) def __new__(cls, *args, **kwargs): declare_field={} for field_name, field in cls.__dict__.items(): if isinstance(field,Fild): declare_field[field_name]=field cls.declare_field=declare_field return object.__new__(cls) def is_valid(self): for field_name,field in self.fields.items(): try: val=self.data.get(field_name) field.valid(val) method = getattr(self, "cleaned_%s" % field_name, None) if method: val=method(val) self.clean_data[field_name]=val except ValidateError as e: self.errors[field_name] = e.detail return len(self.errors) == 0 def __iter__(self): return iter(self.fields.values()) class UserForm(Form): username=CharFiled(error_message={'required':'用户名不能为空'},widget=TextInput()) email=EmailFiled(error_message={'required':'邮箱不能为空','invalid':'格式错误'},widget=EmailInput()) #应用 form =UserForm(data={'username':'ctz','email':'ctz@123'}) if form .is_valid(): print('验证成功',form.clean_data) else : print('验证失败',form.errors)