对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。那么,到底如何实现持久化呢?一种简单的方案是采用硬编码方式,为每一种可能的数据库访问操作提供单独的方法。
class Field(object): def __init__(self, name, colum_type): self.name = name self.colum_type = colum_type def __str__(self): return "<%s:%s>" % (self.__class__.__name__, self.name) class IntegerField(Field): def __init__(self, name): super(IntegerField, self).__init__(name, "bigint") class StringField(Field): def __init__(self, name): super(StringField, self).__init__(name, "varchar(100)") class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if name==‘Model‘: return type.__new__(cls, name, bases, attrs) #将attrs中为数据库类型的变量转移到__mapping__中 mappings = dict() for k, v in attrs.iteritems(): if isinstance(v, Field):#如果是Field类 print(‘Found mapping: %s==>%s‘ % (k, v)) mappings[k] = v#映射到mapping里 for k in mappings.iterkeys(): attrs.pop(k) attrs[‘__table__‘] = name # 假设表名和类名一致 attrs[‘__mappings__‘] = mappings # 保存属性和列的映射关系 return type.__new__(cls, name, bases, attrs) class Model(dict): __metaclass__ = ModelMetaclass def __init__(self, **kw): super(Model, self).__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"‘Model‘ object has no attribute ‘%s‘" % key) def __setattr__(self, key, value): self[key] = value def save(self): fields = [] params = [] args = [] for k, v in self.__mappings__.iteritems(): 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‘ % str(args)) class User(Model): # 定义类的属性到列的映射: id = IntegerField(‘id‘) name = StringField(‘username‘) email = StringField(‘email‘) password = StringField(‘password‘) # 创建一个实例: u = User(id=‘12345‘, name=‘Michael‘, email=‘[email protected]‘, password=‘my-pwd‘) # # 保存到数据库: u.save()