手写ORM第一版
ORM第一版:
#Author = __rianley cheng__ #ORM 简易版 from mysql_ import Mysql class Fileld: def __init__(self,name,colmun_type,primary_key,default): self.name=name self.colmun_type=colmun_type self.primary_key =primary_key self.default=default class Stringfileld(Fileld): def __init__(self,name=None,column_type='varchar(200)',primary_key=False,default=None): super().__init__(name,column_type,primary_key,default) class Interfileld(Fileld): def __init__(self, name=None, column_type='int', primary_key=False, default=0): super().__init__(name, column_type, primary_key, default) class Model_metaclass(type): def __new__(cls, name, bases, attrs): if name == 'Model': return type.__new__(cls, name, bases, attrs) table_name = attrs.get('table_name', None) if not table_name: table_name = name primary_key = None mappings = dict() for k, v in attrs.items(): if isinstance(v, Fileld): # v 是不是Field的对象 mappings[k] = v if v.primary_key: # 找到主键 if primary_key: raise TypeError('主键重复:%s' % k) primary_key = k for k in mappings.keys(): attrs.pop(k) if not primary_key: raise TypeError('没有主键') attrs['table_name'] = table_name attrs['primary_key'] = primary_key attrs['mappings'] = mappings return type.__new__(cls, name, bases, attrs) class Model(dict,metaclass=Model_metaclass): def __init__(self,**kwargs): super(Model,self).__init__(**kwargs) def __getattr__(self, key): # .访问属性触发 try: return self[key] except KeyError: raise AttributeError('没有属性:%s' % key) def __setattr__(self, key, value): self[key] = value @classmethod def select_all(cls, **kwargs): ms = Mysql().singleton() if kwargs: # 当有参数传入的时候 key = list(kwargs.keys())[0] value = kwargs[key] sql = "select * from %s where %s=?" % (cls.table_name, key) sql = sql.replace('?', '%s') res = ms.select(sql, value) else: # 当无参传入的时候查询所有 sql = "select * from %s" % cls.table_name res = ms.select(sql) return [cls(**r) for r in res] @classmethod def select_one(cls, **kwargs): # 此处只支持单一条件查询 key = list(kwargs.keys())[0] value = kwargs[key] ms = Mysql().singleton() sql = "select * from %s where %s=?" % (cls.table_name, key) sql = sql.replace('?', '%s') res = ms.select(sql, value) if res: return cls(**res[0]) else: return None class User(Model): table_name = 'User' id = Interfileld('id','int',primary_key=True,default=0) name = Stringfileld('name') if __name__ == '__main__': user=User().select_one(id='1') user1=User().select_all() print(user) print('=====================>') print(user1)
说明
并非是最终版本! 持续更新中....
每天进步一小点,heiheihei..
作者:rianley cheng
原创作品,转载请注明出处!