Nov
23
2021
Python编程:metaclass元类实现简单的ORM
ORM全称“Object Relational Mapping”,即对象-关系映射
把关系数据库的一行映射为一个对象,一个类对应一个表
这样,写代码更简单,不用直接操作SQL语句。
# -*- coding: utf-8 -*- # @File : 元类实例ORM.py # @Date : 2018-06-01 # @Author : Peng Shiyu # 先定义metaclass,就可以创建类,最后创建实例 class Field(object): """保存数据库表的字段名和字段类型""" def __init__(self, name, column_type): self.name = name self.column_type = column_type def __str__(self): return "<%s %s %s>"%(self.__class__.__name__, self.name, self.column_type) # 定义各种类型 class IntegerField(Field): def __init__(self, name): super(IntegerField, self).__init__(name, "int") class StringField(Field): def __init__(self, name): super(StringField, self).__init__(name, "varchar(255)") # 编写元类 """ 排除掉对Model类的修改; 在当前类(比如User)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个__mappings__的dict中, 同时从类属性中删除该Field属性,否则,容易造成运行时错误(实例的属性会遮盖类的同名属性); 把表名保存到__table__中,这里简化为表名默认为类名。 """ class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if name == "Model": return type.__new__(cls, name, bases, attrs) print("Fond Model: %s"% name) # 查找Field字段 mappings = {} for k, v in attrs.items(): if isinstance(v, Field): print("Fond Field: %s => %s"% (k, v)) mappings[k] = v # 弹出Field字段 for k in mappings.keys(): attrs.pop(k) attrs["__mappings__"] = mappings # 保存属性和列的映射关系 attrs["__table__"] = name # 假设表名和类名一致 return type.__new__(cls, name, bases, attrs) # 在Model类中,就可以定义各种操作数据库的方法,比如save(),delete(),find(),update等等 class Model(dict, metaclass=ModelMetaclass): def __init__(self, **kwargs): super(Model, self).__init__(**kwargs) def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value def save(self): fields = [] params = [] args = [] for k, v in self.__mappings__.items(): fields.append(v.name) params.append("?") args.append(getattr(self, k, None)) sql = "insert into %s (%s) VALUES (%s)"% (self.__table__, ",".join(fields), ",".join(params)) print("sql: %s"% sql) print("args: %s"% args) class User(Model): # 定义类的属性到列的映射: id = IntegerField("id") name = StringField("name") email = StringField("email") password = StringField("password") if __name__ == '__main__': # # 创建一个实例 user = User(id=1, name="Tom", email="12345@qq.com", password="123456") # 保存到数据库 user.save() # 访问元素 print(user.name) print(user["name"]) user.name = "jack" print(user.name) """ Fond Model: User Fond Field: id => <IntegerField id int> Fond Field: name => <StringField name varchar(255)> Fond Field: email => <StringField email varchar(255)> Fond Field: password => <StringField password varchar(255)> sql: insert into User (id,name,email,password) VALUES (?,?,?,?) args: [1, 'Tom', '12345@qq.com', '123456'] Tom Tom jack """
本公司销售:阿里云新/老客户,只要购买阿里云,即可享受折上折优惠!>
我有话说: