一、获取类里面的静态属性以及动态属性的方法

方式一:

# ===========方式一================
class Foo(object):
    user = 123
    def __init__(self):
        self.name = 123
        self.age = 456
    def aaa(self):
        self.name = 'sd'
obj = Foo()
# print(obj.__dict__)  #获取对象属性
# print(Foo.__dict__) #获取类里面的所有属性以及方法等

方式二:

# ===============方式二==================
class Foo2(object):
    A  = 123
    def __init__(self):
        self.name = 'haiyan'
        self.age = 22
        # print(self.__class__.field)  #获取当前类的
    def __new__(cls, *args, **kwargs):
        print(cls.__dict__)
        return object.__new__(cls)

Foo2()

二、自定义Form组件示例

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_message=None, widgets= None):
        self.required = required
        self.error_message = error_message
        if not widgets:
            self.widgets = TextInput()  #设置默认
        else:
            self.widgets = widgets

    def __str__(self):
        # return self.widgets
        return str(self.widgets)  #将对象转成字符串

class CharField(Field):

    def valid(self,val):
        if self.required:
            if not val:
                msg = self.error_message['required']
                raise ValidateError(msg)  #调用自定义的异常
        return val



class EmailField(Field):
    ERG = "^\w+@\w+$"
    def valid(self,val):
        if self.required:
            if not val:
                msg = self.error_message['required']
                raise ValidateError(msg)
        # print(val, type(val))
        result = re.match(self.ERG,val)
        if not result:
            msg = self.error_message.get('invalid','格式错误')
            raise ValidateError(msg)
        return val


# ==========================
class Form(object):
    def __init__(self,data):
        # print(UserForm.__dict__)#获取派生类中的所有静态字段
        # print(self.__class__.__dict__)  #静态动态的获取类中的所有静态字段
        self.data = data
        self.fields = copy.deepcopy(self.__class__.declare_field)  #获取字段
        self.clean_data = {}
        self.errors = {}
    def __new__(cls, *args, **kwargs):  #在__new__里面也可以获取类中的所有静态字段
        declare_field = {}
        for field_name , field in cls.__dict__.items():
            # print(field_name,field)
            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':"zzz","pwd":18}
        # self.fields #{'username': CharField(),"pwd": EmailField()}
        for field_name , field in self.fields.items():
            try:
                input_val = self.data.get(field_name)
                # print("---------------",field_name,input_val)
                val = field.valid(input_val)  #内置的验证规则自己去验证
                method = getattr(self,"clean_%s"%field_name,None)  #默认为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 #根据错误的返回,如果没有错误返回True,有错误返回False

    def  __iter__(self):  ##########自定义生成标签3
        return iter(self.fields.values())  #返回的是一个迭代器

# =======================
class UserForm(Form):
    username = CharField(error_message={'required': '用户名不能为空'}, widgets=TextInput())
    # email = EmailField(error_message={'required': '密码不能为空', 'invalid': '邮箱格式错误'}, widgets=EmailInput())


obj = UserForm(data={'username':"haiyan","email":"dsfsgd"})
if obj.is_valid():
    print(obj.clean_data)
else:
    print(obj.errors)

 

posted on 2018-03-08 19:36  海燕。  阅读(463)  评论(0编辑  收藏  举报