1. 程式人生 > >手寫ORM第一版

手寫ORM第一版

pop singleton .... exc sta 對象 說明 ise list

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

原創作品,轉載請註明出處!

手寫ORM第一版