码迷,mamicode.com
首页 > 其他好文 > 详细

元类实现ORM

时间:2019-01-05 13:24:14      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:meta   arc   简单实现   开发   acl   []   org   ini   __init__   

1. ORM是什么

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

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

demo:

class User(父类省略):
    uid = ('uid', "int unsigned")
    name = ('username', "varchar(30)")
    email = ('email', "varchar(30)")
    password = ('password', "varchar(30)")
    ...省略...


u = User(uid=12345, name='Michael', email='test@orm.org', password='my-pwd')
u.save()
# 对应如下sql语句
# insert into User (username,email,password,uid)
# values ('Michael','test@orm.org','my-pwd',12345)

说明

  1. 所谓的ORM就是让开发者在操作数据库的时候,能够像操作对象时通过xxxx.属性=yyyy一样简单,这是开发ORM的初衷
  2. 只不过ORM的实现较为复杂,Django中已经实现了 很复杂的操作,本节知识 主要通过完成一个 insert相类似的ORM,理解其中的道理就就可以了

2. 通过元类简单实现ORM中的insert功能

class ModelMetaClass(type):

    def __new__(cls, class_name, class_parents, class_attrs):

        mapping = dict()

        for name, value in class_attrs.items():
            if isinstance(value, tuple):
                print("Found mapping %s --> %s" % (name, value))
                mapping[name] = value

        for name in mapping.keys():
            class_attrs.pop(name)

        class_attrs["__mapping__"] = mapping
        class_attrs["__table__"] = class_name

        return type.__new__(cls, class_name, class_parents, class_attrs)

class User(metaclass=ModelMetaClass):
    uid = ('uid', "int unsigned")
    name = ('username', "varchar(30)")
    email = ('email', "varchar(30)")
    password = ('password', "varchar(30)")

    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])
            args.append(getattr(self, k, None))

        sql = "insert into %s(%s) values(%s)" % (self.__table__, ",".join(fields), ",".join([str(i) for i in args]))
        print("SQL: %s" % sql)


u = User(uid=123, name="zfx", email="zfx@zfx.com", password="6666")
u.save()

执行的效果:

Found mapping uid --> ('uid', 'int unsigned')
Found mapping name --> ('username', 'varchar(30)')
Found mapping password --> ('password', 'varchar(30)')
Found mapping email --> ('email', 'varchar(30)')
SQL: insert into User(uid,password,email,username) values(123,6666,zfx@zfx.com,zfx)

3. 完善对数据类型的检测

class ModelMetaClass(type):

    def __new__(cls, class_name, class_parents, class_attrs):

        mapping = dict()

        for name, value in class_attrs.items():
            if isinstance(value, tuple):
                print("Found mapping %s --> %s" % (name, value))
                mapping[name] = value

        for name in mapping.keys():
            class_attrs.pop(name)

        class_attrs["__mapping__"] = mapping
        class_attrs["__table__"] = class_name

        return type.__new__(cls, class_name, class_parents, class_attrs)

class User(metaclass=ModelMetaClass):
    uid = ('uid', "int unsigned")
    name = ('username', "varchar(30)")
    email = ('email', "varchar(30)")
    password = ('password', "varchar(30)")

    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])
            args.append(getattr(self, k, None))

        args_v = []
        for arg in args:
            if isinstance(arg, int):
                args_v.append(str(arg))
            else:
                args_v.append("""'%s'""" % arg)

        sql = "insert into %s(%s) values(%s)" % (self.__table__, ",".join(fields), ",".join(args_v))
        print("SQL: %s" % sql)


u = User(uid=123, name="zfx", email="zfx@zfx.com", password="6666")
u.save()

执行的效果:

Found mapping uid --> ('uid', 'int unsigned')
Found mapping password --> ('password', 'varchar(30)')
Found mapping email --> ('email', 'varchar(30)')
Found mapping name --> ('username', 'varchar(30)')
SQL: insert into User(password,uid,username,email) values('6666',123,'zfx','zfx@zfx.com')

4. 抽取到基类中

class ModelMetaClass(type):

    def __new__(cls, class_name, class_parents, class_attrs):

        mapping = dict()

        for name, value in class_attrs.items():
            if isinstance(value, tuple):
                print("Found mapping %s --> %s" % (name, value))
                mapping[name] = value

        for name in mapping.keys():
            class_attrs.pop(name)

        class_attrs["__mapping__"] = mapping
        class_attrs["__table__"] = class_name

        return type.__new__(cls, class_name, class_parents, class_attrs)

class Model(metaclass=ModelMetaClass):

    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])
            args.append(getattr(self, k, None))

        args_v = []
        for arg in args:
            if isinstance(arg, int):
                args_v.append(str(arg))
            else:
                args_v.append("""'%s'""" % arg)

        sql = "insert into %s(%s) values(%s)" % (self.__table__, ",".join(fields), ",".join(args_v))
        print("SQL: %s" % sql)


class User(Model):
    uid = ('uid', "int unsigned")
    name = ('username', "varchar(30)")
    email = ('email', "varchar(30)")
    password = ('password', "varchar(30)")


u = User(uid=123, name="zfx", email="zfx@zfx.com", password="6666")
u.save()

元类实现ORM

标签:meta   arc   简单实现   开发   acl   []   org   ini   __init__   

原文地址:https://www.cnblogs.com/zhangfengxian/p/10223817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!