orm1.0

class Field:
    def __init__(self,name,column_type,primary_key,defaule):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = defaule

class IntegerField(Field):
    def __init__(self,name,column_type = 'int',primary_key = False,default = 0):
        super().__init__(name,column_type,primary_key ,default )

class StringField(Field):
    def __init__(self,name,column_type = 'varchar(64)',primary_key = False,default = None):
        super().__init__(name,column_type,primary_key ,default )


class OrmMetaClass(type):
    def __new__(cls, class_name,class_bases,class_attr):

        if class_name == 'Models':
            return type. __new__(cls, class_name,class_bases,class_attr)

        table_name = class_attr.get('table_name',class_name)

        primary_key = None
        mappings = {}

        for k,v in class_attr.items():
            if isinstance(v,Field):
                mappings[k] = v
                if v.primary_key:
                    if primary_key:
                        raise TypeError('only need one primary key')

                    primary_key = v.primary_key

        for k in mappings:
            class_attr.pop(k)

        if  not primary_key:
            raise TypeError('a primary key is necessary')

        class_attr['primary_key'] = primary_key
        class_attr['table_name'] = table_name
        class_attr['mappings'] = mappings

        return type.__new__(cls, class_name,class_bases,class_attr)



class Models(dict,metaclass=OrmMetaClass):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)


    def __getattr__(self, item):
        return self.get(item)

    def __setattr__(self, key, value):
        self[key] = value


class User(Models):
    user_id = IntegerField(name = 'user_id',primary_key=True)
    user_name = StringField(name = 'user_name',)
    user_pwd = StringField(name = 'user_pwd')

if __name__ == '__main__':
    user = User()
    user.name = 'agsol'
    user.id = 1
    user.pwd = '123'

    print(user)
    print(user.name)







posted @ 2019-11-04 22:41  Agsol  阅读(130)  评论(0编辑  收藏  举报