第四十一节 ORM介绍和用元类实现

'''
ORM是python编程语言后端web框架Django的核心思想,'Object Relational Mapping' 即对象-关系映射
简称'ORM'

一句话理解就是:创建一个实例对象,用它创建它的类名当做数据表名,用它创建类属性对应的数据表的字段,
当这个实例对象操作时,能够对应MySQL语句
'''

class Model_Mtaclass(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['__mapping__'] = mappings  # 保存属性和列的映射
        attrs['__table__'] = name  # 假设表名和类名一致
        return type.__new__(cls, name, bases, attrs)


class User(metaclass=Model_Mtaclass):
    uid = ('uid','int unsigned')
    name = ('username', 'varchar(30)')
    email = ('email', 'varchar(30)')
    password = ('password', 'varchar(30)')
    # 指定元类以后,以上的类属性将不在累中,而是在__mapping__属性指定的字典存储

    def __init__(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)
            # 将字典中的键值对取出放入实例对象空间

    def save(self):
        fields = []
        args = []
        for k, v in self.__mapping__.items():
            fields.append(v[0])
            print(k,v)
            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 = 'xxxx', email = 'xxxxx@.163.com', password = 'xxxx')

u.save()

 

posted @ 2020-04-10 17:26  kog_maw  阅读(144)  评论(0编辑  收藏  举报