class ModeMetaclass(type):
def __new__(cls, name, bases, attrs):
mappings = dict()
# 判斷是否需要儲存
for k, v in attrs.items():
# 判斷是否是指定的StringField或者IntegerField的執行個體對象
if isinstance(v, tuple):
# print('Found mapping: %s ==> %s' % (k, v))
mappings[k] = v
# 删除這些已經在字典中存儲的屬性
for k in mappings.keys():
attrs.pop(k)
# 将之前的uid\name\email\password以及對應得對象引用、類名字
attrs['__mappings__'] = mappings # 儲存屬性和列的映射關系
attrs['__table__'] = name # 假設表名和類名一緻
return type.__new__(cls, name, bases, attrs)
class User(metaclass=ModeMetaclass):
uid = ('uid', 'int unsigned')
name = ('name', 'varchar(30)')
email = ('email', 'varchar(30)')
password = ('password', 'varchar(30)')
# 當指定元類之後,以上的類屬性将不在類中,而是在__mappings__屬性指定的字典中存儲
#__mappings__ = {
# 'uid':('uid','int unsigned')
# 'name':('name','varchar(30)')
# 'email':('email','varchar(30)')
# 'password':('password','varchar(30)')
#}
__table__ = 'User'
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
# 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))
# sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join([str(i) for i in args]))
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 = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp))
print('SQL: %s' % sql)
u = User(uid = 12345, name='Michael', email = '[email protected]', password='my-pwd')
# print(u.__dict__)
u.save()