摘抄于《python-3-廖雪峰》
使用ORM框架
class User(Model):
#定义类的属性到列的映射:
id = IntegerFiled('id')
name = StringField('username')
email = StringField('email')
password = StringField('password')
#创建一个实例
u = User(id = 12345, name='Michael', email='test@orm.org',password='my-pwd')
#保存到数据库
u.save()
使用上面的接口来实现ORM
使用field类,它负责数据库表的字段名和字段类型:
class Field(object):
def __init__(self, name, column_type):
self.name = name
self.column_type = column_type
def __str__(self):
return '<%s:%s>' % (self.__class__.__name__, self.name)
定义StringField,IntegerField
class StringField(Field):
def __init__(self, name):
super(StringField, self).__init__(name, 'varchar(100)')
class IntegerField(Field):
def __init__(self, name):
super(IntegerField, self).__init__(name, 'bigint')
编写ModelMetaclass
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
if name=='Model':
return type.__new__(cls, name, bases, attrs)
print('Found model: %s' % name)
mappings = dict()
for k, v in attrs.items():
if isinstance(v, Field):
print('Found mapping: %s ==> %s' % (k, v))
mappings[k] = v
for k in mappings.keys():
atrrs.pop(k)
attrs['__mappings__'] = mappings #保存属性和列的映射关系
attrs['__table__'] = name #假设表名和类名一致
reutrn type.__new__(cls, name, bases, attrs)
基类Model:
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_:
fileds = []
params = []
args = []
for k, v in self.__mappings__.item():
fields.append(v.name)
params.append('?')
args.append(getattr(self, k, None))
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fileds), ','.join(params))
print('SQL: %s' % sql)
print('ARGS: %s % str(args))