import re import copy 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 Field(object): def __init__(self,required=True,error_messages=None,widget=None): self.required = required self.error_messages = error_messages if not widget: self.widget = TextInput() else: self.widget = widget def __str__(self): return str(self.widget) class CharField(Field): def valid(self,val): if self.required: if not val: msg = self.error_messages[‘required‘] raise ValidateError(msg) return val class EmailField(Field): REG = "^\[email protected]\w+$" def valid(self,val): if self.required: if not val: msg = self.error_messages[‘required‘] raise ValidateError(msg) result = re.match(self.REG,val) if not result: msg = self.error_messages.get(‘invalid‘,‘格式错误‘) raise ValidateError(msg) return val # ###################### Form,获取用户提交内容+获取定义的字段对象 class Form(object): def __init__(self,data=None): # 获取派生类中的所有静态字段 # print(self.__class__.__dict__) self.data = data self.fields = copy.deepcopy(self.__class__.declare_field) self.cleaned_data = {} self.errors = {} def __new__(cls, *args, **kwargs): declare_field = {} for field_name, field in cls.__dict__.items(): if isinstance(field,Field): declare_field[field_name] = field cls.declare_field = declare_field return object.__new__(cls) def is_valid(self): # 用户提交的数据 # self.data # {"username":"alex","pwd":18,‘xxx‘:11} # self.fields # {"username":CharField(), "pwd": EmailField() } for field_name,filed in self.fields.items(): try: input_val = self.data.get(field_name) val = filed.valid(input_val) method = getattr(self,"cleaned_%s" %field_name,None) if method: val = method(val) self.cleaned_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 = CharField(error_messages={‘required‘:‘用户名不能为空‘},widget=TextInput()) pwd = EmailField(error_messages={‘required‘:‘密码不能为空‘,‘invalid‘:‘密码格式错误‘},widget=EmailInput()) # ############### 应用 obj = UserForm(data={"username":"sdf","pwd":"sdf",‘xxx‘:666}) if obj.is_valid(): print(‘验证成功‘,obj.cleaned_data) else: print("验证失败",obj.errors) # ##################### HTML ##################### for x in obj: print(x)