Using Metaclass to implement a streamlined ORM framework

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.