Archive:
1 #-*-coding:utf-8-*-2 classField (object):3 4 def __init__(self, Name, Column_type):5Self.name =name6Self.column_type =Column_type7 8 def __str__(self):9 return '<%s:%s>'% (self.__class__.__name__, Self.name)Ten classStringfield (Field): One A def __init__(self, name): -Super (Stringfield, self).__init__(Name,'varchar (+)') - the classIntegerfield (Field): - - def __init__(self, name): -Super (Integerfield, self).__init__(Name,'bigint') + classModelmetaclass (type): - + def __new__(CLS, name, bases, attrs): A ifname=='Model': at returnType.__new__(CLS, name, bases, Attrs) - Print('Found Model:%s'%name) -mappings =dict () - forKvinchAttrs.items (): - ifisinstance (V, Field): - Print('Found Mapping:%s ==>%s'%(k, v)) inMAPPINGS[K] =v - forKinchMappings.keys (): to Attrs.pop (k) +attrs['__mappings__'] = Mappings#Saving mappings for properties and columns -attrs['__table__'] = Name#Assuming that the table name and class name match the returnType.__new__(CLS, name, bases, Attrs) * classModel (Dict, metaclass=modelmetaclass): $ Panax Notoginseng def __init__(Self, * *kw): -Super (Model, self).__init__(**kw) the + def __getattr__(self, key): A Try: the returnSelf[key] + exceptKeyerror: - RaiseAttributeerror (R"' Model ' object has no attribute '%s '"%key) $ $ def __setattr__(self, Key, value): -Self[key] =value - the defSave (self): -Fields = []Wuyiparams = [] theargs = [] - forKvinchSelf.__mappings__. Items (): Wu fields.append (v.name) -Params.append ('?') About 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)) - classUser (Model): A #to define a property-to-column mapping for a class: +id = Integerfield ('ID') theName = Stringfield ('username') -email = Stringfield ('Email') $Password = Stringfield ('Password') the #Create an instance: theU = User (id=12345, name='Michael', email='[email protected]', password='my-pwd') the #Save to database: theU.save ()
The results are as follows:
Found Model:user
Found Mapping:id ==> <IntegerField:id>
Found mapping:name ==> <StringField:username>
Found Mapping:email ==> <StringField:email>
Found Mapping:password ==> <StringField:password>
Sql:insert into User (Id,username,email,password) VALUES (?,?,?,?)
ARGS: [12345, ' Michael ', ' [email protected] ', ' my-pwd ']
[Finished in 0.2s]
Using Metaclass to implement a streamlined ORM framework