(推荐操作系统:windows7系统Python 3.9.1、DELL G3电脑。)
1、定义Field类,它负责保存数据库表的字段名和字段类型:
classField(object): def__init__(self,name,column_type): self.name=name self.column_type=column_type
2、在Field的基础上,进一步定义StringField、IntegerField等各种特定类型的Field:
classStringField(Field): def__init__(self,name,max_length): super(StringField,self).__init__(name,'varchar(%d)'%max_length) classIntegerField(Field): def__init__(self,name): super(IntegerField,self).__init__(name,'int')
3、下一步是编写最复杂的ModelMetaclass:
classModelMetaclass(type): def__new__(cls,name,bases,attrs): ifname=='Model': returntype.__new__(cls,name,bases,attrs) print('Foundmodel:%s'%name) mappings=dict() fork,vinattrs.items(): ifisinstance(v,Field): mappings[k]=v forkinmappings.keys(): attrs.pop(k) attrs['__mappings__']=mappings attrs['__table__']=name returntype.__new__(cls,name,bases,attrs)
4、创建User类,并使用save方法保存:
classUser(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,希望对大家有所帮助。更多Python学习指导:python基础教程