python簡單實(shí)現(xiàn)了一個ORM
(推薦操作系統(tǒng):windows7系統(tǒng)、Python3.9.1、DELLG3電腦。)
1、定義Field類,它負(fù)責(zé)保存數(shù)據(jù)庫表的字段名和字段的類型:
classField(object):
def__init__(self,name,column_type):
self.name=name
self.column_type=column_type
2、在Field的基礎(chǔ)上,進(jìn)一步定義各種具體類型的Field,比如StringField,IntegerField等等:
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、下一步,就是編寫最復(fù)雜的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、創(chuàng)建User類,并調(diào)用save方法,保存:
classUser(Model):
id=IntegerField('id')
name=StringField('username',max_length=48)
email=StringField('email',max_length=128)
password=StringField('password',max_length=24)
#創(chuàng)建一個實(shí)例:
u=User(id=12345,name='xiaoming',email='xiaoming@xiaomi.com',password='test')
#保存到數(shù)據(jù)庫:
u.save()
以上就是python簡單實(shí)現(xiàn)了一個ORM,希望能對大家有所幫助。更多Python學(xué)習(xí)教程請關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。