1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
__author__ = 'lenovo'
class ModelMetalclass(type): def __new__(cls, name, bases, attrs): mappings = dict()
for k,v in attrs.items(): if isinstance(v, tuple): mappings[k] = v
for k in mappings.keys(): attrs.pop(k)
attrs['__mappings__'] = mappings attrs['__table__'] = name
return type.__new__(cls,name,bases,attrs)
class User(metaclass=ModelMetalclass): uid = ('uid',"int unsigned") name = ('username',"varchar(30") email = ('email' , "varchar(30)") password = ('password',"varchar(30)")
def __init__(self,**kwargs): for name,value in kwargs.items(): setattr(self,name,value)
def save(self): fields = [] args = [] for k,v in self.__mappings__.items(): fields.append(v[0]) args.append(getattr(self,k,None))
args_temp = list() for temp in args: if isinstance(temp,int): args_temp.append(str(temp)) elif isinstance(temp,str): args_temp.append("""'%s'"""%temp)
sql = 'inser into %s (%s) values (%s);'%(self.__table__,','.join(fields),','.join(args_temp))
print('SQL:%s'%sql)
user =User(uid=12345,name='LS',email='xxx@qq.com',password='pwd')
user.save()
|