Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Field(object):
- def __init__(self, name, column_type):
- self.name = name
- self.column_type = column_type
- def __str__(self):
- return '<%s:%s>' % (self.__class__.__name__, self.name)
- class StringField(Field):
- def __init__(self, name):
- super(StringField, self).__init__(name, 'varchar(100)')
- class IntegerField(Field):
- def __init__(self, name):
- super(IntegerField, self).__init__(name, 'bigint')
- class Model(dict):
- __db__ = 'db_name'
- def __new__(cls, **kws):
- cls.__table__ = cls.__name__
- cls.__mappings__ = {k: getattr(cls, k) for k in dir(
- cls) if isinstance(getattr(cls, k), Field)}
- return super().__new__(cls, **kws)
- def __init__(self, **kws):
- for k in self.__mappings__.keys():
- setattr(self, k, kws.get(k))
- _kws = {k: v for k, v in kws.items() if k in self.__mappings__.keys()}
- super().__init__(**_kws)
- def __setattr__(self, key, value):
- print('set: ', key, '--->', value)
- if key not in self.__mappings__.keys():
- raise AttributeError(r'unavailable key: %s' % key)
- self[key] = value
- super().__setattr__(key, value)
- def save(self):
- fields = []
- params = []
- args = []
- for k, v in self.__mappings__.items():
- fields.append(v.name)
- params.append('?')
- 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))
- class User(Model):
- id = IntegerField('id')
- name = StringField('username')
- email = StringField('email')
- password = StringField('password')
- class SubUser(User):
- nickname = StringField('nickname')
- if __name__ == '__main__':
- u = User(id=123, name='Michael', email='test@orm.org', password='my-pwd')
- u.save()
Add Comment
Please, Sign In to add comment