Custom assembly tornado Form

First, access to which type of static attributes and dynamic attributes Method

method one:

# =========== a manner ================ 
class Foo (Object): 
    User = 123
     DEF  the __init__ (Self): 
        the self.name = 123 
        self.age = 456
     DEF AAA (Self): 
        the self.name = ' SD ' 
obj = Foo ()
 # Print (obj .__ dict__ magic) obtaining object attribute # 
# Print (Foo .__ dict__ magic) # acquired all class attributes and methods which Wait

Second way:

# =============== embodiment two ================== 
class Foo2 (Object): 
    A   = 123
     DEF  the __init__ (Self) : 
        the self.name = ' Haiyan ' 
        self.age = 22 is
         # Print (Self Field .__ class __.) # Get the current class 
    DEF  __new__ is (CLS, args *, ** kwargs):
         Print (CLS. the __dict__ )
         return Object. __new__ is (CLS) 

Foo2 ()

Second, custom Form Component Example

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">'


============ fields: a verification inside a regular ======================#
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']
                The raise ValidateError (MSG)
         # Print (Val, type (Val)) 
        Result = re.match (self.ERG, Val)
         IF  Not Result: 
            MSG = self.error_message.get ( ' invalid ' , ' malformed ' )
             The raise ValidateError (MSG)
         return Val 


# ========================== 
class Form1 (Object):
     DEF  the __init__ (Self, Data):
         # Print (the UserForm .__ dict __) # get all the static fields derived class 
        # Print (Self .__ class __.__ dict__) # static and dynamic access to all the static fields of the class
        = self.data Data 
        self.fields = copy.deepcopy (. Self the __class__ .declare_field)   # acquires field 
        self.clean_data = {} 
        self.errors = {}
     DEF  __new__ is (CLS, args *, ** kwargs):   # in _ _new__ which may also get all static fields class 
        declare_field = {}
         for FIELD_NAME, field in CLS. the __dict__ .items ():
             # Print (FIELD_NAME, field) 
            IF the 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)  #Built own validation rules to validate 
                Method = getattr (Self, " clean_% S " % FIELD_NAME, None)   # Default is None 
                IF Method: 
                    Val = Method (Val) 
                self.clean_data [FIELD_NAME] = Val
             the except ValidateError AS E: 
                Self .errors [FIELD_NAME] = e.detail
         return len (self.errors) == 0 # according to the error return True if no error is returned, an error is returned False 

    DEF   the __iter__ (Self):   # ######## generating a custom tag #. 3 
        return ITER (self.fields.values ())   #It returns an iterator 

# ======================= 
class the UserForm (Form1): 
    username = as CharField (ERROR_MESSAGE = { ' required ' : ' username can not be empty ' }, Widgets = the TextInput ())
     # In email = EmailField (ERROR_MESSAGE = {' required ':' password can not be empty ',' invalid ':' E-mail format error '}, Widgets = EmailInput ()) 


obj = the UserForm ({Data = ' username ' : " Haiyan " , " In Email " : " dsfsgd " })
 IF obj.is_valid ():
    print(obj.clean_data)
else:
    print(obj.errors)

 

Guess you like

Origin www.cnblogs.com/zcfx/p/11326388.html