from orm.mysql_class import MySql class Field(object): def __init__(self, name, field_type, primary_key, default): self.name = name self.field_type = field_type self.primary_key = primary_key self.default = default class StringField(Field): def __init__(self,name,field_type='varchar',primary_key=False,default=None): super(StringField, self).__init__(name, field_type, primary_key, default) class IntegerField(Field): def __init__(self,name,field_type='int',primary_key=False,default=0): super(IntegerField, self).__init__(name, field_type, primary_key, default) class MyMetaClass(type): def __new__(cls, class_name, class_bases, class_attrs): if class_name == 'Models': return type.__new__(cls, class_name, class_bases, class_attrs) table_name = class_attrs.get('table_name',class_name) primary_key = None mappings = {} for k, v in class_attrs.items(): if isinstance(v,Field): mappings[k] = v if v.primary_key: if primary_key: raise TypeError('只能有一个主键') primary_key = v.name for i in mappings: class_attrs.pop(i) if not primary_key: raise TypeError('没有主键') class_attrs['table_name'] = table_name class_attrs['primary_key'] = primary_key class_attrs['mappings'] = mappings return type.__new__(cls, class_name, class_bases, class_attrs) class Models(dict,metaclass=MyMetaClass): def __init__(self,**kwargs): super().__init__(**kwargs) def __getattr__(self, item): return self.get(item, '没有这个字段') def __setattr__(self, key, value): self[key] = value @classmethod def my_select(cls,**kwargs): md = MySql() if not kwargs: sql = "select * from %s"%cls.table_name res = md.select(sql) else: key = list(kwargs.keys())[0] values = kwargs.get(key) sql = "select * from %s where %s=?"%(cls.table_name,key) sql = sql.replace('?','%s') res = md.select(sql,values) print(res) if res: return [cls(**i) for i in res] def my_insert(self): ms = MySql() keys = [] values = [] wenhao = [] for k,v in self.mappings.items(): if not v.primary_key: keys.append(v.name) values.append(getattr(self,v.name,v.default)) wenhao.append('?') sql = "insert into %s(%s) values(%s)"%(self.table_name,','.join(keys),','.join(wenhao)) sql = sql.replace('?','%s') ms.execute(sql,values) def my_update(self): ms = MySql() field = [] values = [] primary_key = None for k, v in self.mappings.items(): if v.primary_key: primary_key = getattr(self,v.name,v.default) else: field.append(v.name+'=?') values.append(getattr(self,v.name)) sql = "update %s set %s where %s=%s"%( self.table_name, ','.join(field), self.primary_key, primary_key ) print(self.primary_key) print(primary_key) sql = sql.replace('?','%s') ms.execute(sql,values)