元编程实现ORM

文章借鉴 [https://www.cnblogs.com/tkqasn/p/6524879.html]

!/usr/bin/python

-- coding: UTF-8 --

class Field(object):
def init(self, name, cl_ype):
self.name = name
self.cl_type = cl_ype

class StringField(Field):

def __init__(self, name):
    super(StringField, self).__init__(name, 'varchar(100)')

class IntField(Field):
def init(self, name):
super(IntField, self).init(name, 'bigint')

class ModelMeta(type):

def __new__(cls, name, base, attr):
    if __name__ == 'Model':
        return super(ModelMeta, cls).__new__(cls, name, base, attr)
    mappings = dict()
    for k, v in attr.iteritems():
        if isinstance(v, Field):
            mappings[k] = v
    for k in mappings.iterkeys():
        attr.pop(k)

    attr['__table__'] = name
    attr['__mappings__'] = mappings
    return super(ModelMeta, cls).__new__(cls, name, base, attr)

class Model(dict):
metaclass = ModelMeta

def __init__(self, **kwargs):
    super(Model, self).__init__(**kwargs)

def __getattr__(self, key):
    try:
        return self[key]
    except KeyError:
        raise AttributeError('{} has not attribut {}'.format(self, key))

def __setattr__(self, key, value):
    self[key] = value

def save(self):
    cls = self.__class__
    field = []
    para = []
    for k, v in cls.__mappings__.iteritems():
        field.append(v.name)
        para.append('?')

    sql = 'insert into {} ({}) values ({})'.format(cls.__table__, ','.join(field), ','.join(para))
    print sql

class User(Model):
name = StringField('name')
age = IntField('age')

u = User(name='liuxue', age=30)
u.save()

你可能感兴趣的:(元编程实现ORM)