fork download
  1. # your code goes here
  2. class Field(object):
  3.  
  4. def __init__(self, name, column_type):
  5. self.name = name
  6. self.column_type = column_type
  7.  
  8. def __str__(self):
  9. return '<%s:%s>' % (self.__class__.__name__, self.name)
  10.  
  11. class StringField(Field):
  12. def __init__(self, name):
  13. super(StringField, self).__init__(name, 'varchar(100)')
  14.  
  15. class IntegerField(Field):
  16. def __init__(self, name):
  17. super(IntegerField, self).__init__(name, 'bigint')
  18.  
  19. class ModelMetaclass(type):
  20. def __new__(cls, name, bases, attrs):
  21. if name=='Model':
  22. return type.__new__(cls, name, bases, attrs)
  23. print('Found model: %s' % name)
  24. mappings = dict()
  25. for k, v in attrs.items():
  26. if isinstance(v, Field):
  27. print('Found mapping: %s ==> %s' % (k, v))
  28. mappings[k] = v
  29. for k in mappings.keys():
  30. attrs.pop(k)
  31. attrs['__mappings__'] = mappings # 保存属性和列的映射关系
  32. attrs['__table__'] = name # 假设表名和类名一致
  33. return type.__new__(cls, name, bases, attrs)
  34.  
  35. class Model(dict, metaclass=ModelMetaclass):
  36. def __init__(self, **kw):
  37. super(Model, self).__init__(**kw)
  38.  
  39. def __getattr__(self, key):
  40. try:
  41. temp=self[key]
  42. print('quoted')
  43. return temp
  44. except KeyError:
  45. raise AttributeError(r"'Model' object has no attribute '%s'" % key)
  46.  
  47. def __setattr__(self, key, value):
  48. self[key] = value
  49.  
  50. def save(self):
  51. fields = []
  52. params = []
  53. args = []
  54. for k, v in self.__mappings__.items():
  55. fields.append(v.name)
  56. params.append('?')
  57. args.append(getattr(self, k, None))
  58. sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
  59. print('SQL: %s' % sql)
  60. print('ARGS: %s' % str(args))
  61. class User(Model):
  62. # 定义类的属性到列的映射:
  63. id = IntegerField('id')
  64. name = StringField('username')
  65. email = StringField('email')
  66. password = StringField('password')
  67.  
  68. # 创建一个实例:
  69. u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
  70. # 保存到数据库:
  71. u.save()
Success #stdin #stdout 0.04s 9584KB
stdin
Standard input is empty
stdout
Found model: User
Found mapping: id ==> <IntegerField:id>
Found mapping: name ==> <StringField:username>
Found mapping: email ==> <StringField:email>
Found mapping: password ==> <StringField:password>
quoted
quoted
quoted
quoted
SQL: insert into User (id,username,email,password) values (?,?,?,?)
ARGS: [12345, 'Michael', 'test@orm.org', 'my-pwd']