python中通过元类(TYPE)简单实现对象关系映射(ORM)
2020-12-13 05:40
标签:需要 字段 keyword base 代码 完整 表头 type 数据库 ORM是创建一个实例对象,用创建他的类名当做数据表名,用创建他的类属性对应数据表的字段,不需要在自己写复杂的sql语句,而是通过对实例对象的操作时,能让代码自动帮我们整理为对应的sql语句。 类似下图创建一个实例对象,把数据库的数据以参数入 通过调用某个方法,ORM自动帮我们整理为下面代码并执行: 从而大大简化我们的工作,减少出错率!下面是完整代码(通过metaclass可以指定我们需要继承的元类): 需要注意的点: python中通过元类(TYPE)简单实现对象关系映射(ORM) 标签:需要 字段 keyword base 代码 完整 表头 type 数据库 原文地址:https://www.cnblogs.com/lzb888/p/11145901.htmlclass User(父类):
uid = ("uid", "int unsigned")
name = ("username", "varchar(20)")
password = ("password", "varchar(20)")
...省略...
uid
username
password
u = User(nid=12345, name="laowang",password="123321")
insert into (uid,name,password) value (12345,"laowang","123321")
class Mode_type(type):
def __new__(cls, name, bases, attrs)
mappings = dict()
for k, v in attrs.items():
if isinstanse(v, tuple):
mappings[k] = v
# 找到新字典接收完attrs的数据后,删掉attrs里的数据
for k in mappings.keys[]:
attrs.pop(k)
# 将之前新字典保存的数据表的信息保存在attrs中
attrs["__mappings__"] = mappings
# name指向新创建的实例对象名,相当于保存数据表的名称
attrs["__table__"] = name
return type.__new__(cls, name, bases, attrs)
class User(mateclass = Mode_type):
uid = ("uid", "int unsigned")
name = ("username", "varchar(20)")
password = ("password", "varchar(20)")
# 指定元类后,以上的类属性就不在类中,而是在__mapping__指定的字典中仓储
# 类似于
# __mapping__ = {
# uid :("uid", "int unsigned")
# name: ("username", "varchar(20)")
# password :("password", "varchar(20)")
# }
# __table__ = "User"
def __init__(self, **kwargs):
# 取出字典里面的值
for name, value in kwargs.items():
setattr(self, name, value)
# 这里不能用self.name = value ,这样只会让实例对象拥有name这个属性,而不是name形参背后真正替换的属性,所以用setattr
def save()
# 数据表表头字段
fields = []
# 数据表字段对应的数据
args = []
for k, v in self.__mappings__.items():
field.append(v[0])
args.append(getattr(self, k, None))
args_temp = list()
# 区分参数的类型,防止写入数据表后报错
for temp in args:
if isinstence(temp, int):
args_temp.append(str(temp)) # 类似temp = “123456”
elif isinstence(temp, str):
args_temp.append("""%s""" % temp) # 类似temp = """‘123321‘"""
sql = "insert into %s (%s) value (%s)" % (self.__table__, ",".join(fields), ",".join(args_temp))
# 下面就可以执行mysql的操作,只是说ORM,所以我只打印了这句话
print(sql)
u = User(uid = 123456, name="laowang", password = "123321")
u.save()
etaclass是类的模板,所以必须从`type`类型继承:
选择__new__函数作为实现"修改类"的函数:
u = type(‘User‘, (object,),{uid:("uid", "int unsigned"),name :("username", "varchar(20)"),password:("password", "varchar(20)"})
上一篇:【2014 Multi-University Training Contest 3 1002】/【HDU 4888】 Redraw Beautiful Drawings
下一篇:service structure flowchart [mobile to server via HTTP RESTful API]
文章标题:python中通过元类(TYPE)简单实现对象关系映射(ORM)
文章链接:http://soscw.com/essay/31531.html