1、定义Field类,它负责保存数据库表的字段名和字段的类型:
class Field(object): def __init__(self, name, column_type): self.name = name self.column_type = column_type
2、在Field的基础上,进一步定义各种具体类型的Field,比如StringField,IntegerField等等:
class StringField(Field): def __init__(self, name, max_length): super(StringField, self).__init__(name, 'varchar(%d)' % max_length) class IntegerField(Field): def __init__(self, name): super(IntegerField, self).__init__(name, 'int')
3、下一步,就是编写最复杂的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): mappings[k] = v for k in mappings.keys(): attrs.pop(k) attrs['__mappings__'] = mappings attrs['__table__'] = name return type.__new__(cls, name, bases, attrs)
4、创建User类,并调用save方法,保存:
class User(Model): id = IntegerField('id') name = StringField('username', max_length=48) email = StringField('email', max_length=128) password = StringField('password', max_length=24) # 创建一个实例: u = User(id=12345, name='xiaoming', email='xiaoming@xiaomi.com', password='test') # 保存到数据库: u.save()
以上就是python简单实现了一个ORM,希望能对大家有所帮助。
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试