SHOW:
|
|
- or go back to the newest paste.
1 | class Field(object): | |
2 | def __init__(self, name, column_type): | |
3 | self.name = name | |
4 | self.column_type = column_type | |
5 | ||
6 | def __str__(self): | |
7 | return '<%s:%s>' % (self.__class__.__name__, self.name) | |
8 | ||
9 | ||
10 | class StringField(Field): | |
11 | def __init__(self, name): | |
12 | super(StringField, self).__init__(name, 'varchar(100)') | |
13 | ||
14 | ||
15 | class IntegerField(Field): | |
16 | def __init__(self, name): | |
17 | super(IntegerField, self).__init__(name, 'bigint') | |
18 | ||
19 | ||
20 | class Model(dict): | |
21 | __db__ = 'db_name' | |
22 | ||
23 | def __new__(cls, **kws): | |
24 | ||
25 | cls.__table__ = cls.__name__ | |
26 | cls.__mappings__ = {k: getattr(cls, k) for k in dir( | |
27 | cls) if isinstance(getattr(cls, k), Field)} | |
28 | ||
29 | return super().__new__(cls, **kws) | |
30 | ||
31 | def __init__(self, **kws): | |
32 | for k in self.__mappings__.keys(): | |
33 | setattr(self, k, kws.get(k)) | |
34 | ||
35 | _kws = {k: v for k, v in kws.items() if k in self.__mappings__.keys()} | |
36 | super().__init__(**_kws) | |
37 | ||
38 | def __setattr__(self, key, value): | |
39 | ||
40 | print('set: ', key, '--->', value) | |
41 | if key not in self.__mappings__.keys(): | |
42 | raise AttributeError(r'unavailable key: %s' % key) | |
43 | self[key] = value | |
44 | super().__setattr__(key, value) | |
45 | ||
46 | def save(self): | |
47 | fields = [] | |
48 | params = [] | |
49 | args = [] | |
50 | for k, v in self.__mappings__.items(): | |
51 | fields.append(v.name) | |
52 | params.append('?') | |
53 | args.append(getattr(self, k, None)) | |
54 | ||
55 | sql = 'insert into %s (%s) values (%s)' % ( | |
56 | self.__table__, ','.join(fields), ','.join(params)) | |
57 | print('SQL: %s' % sql) | |
58 | print('ARGS: %s' % str(args)) | |
59 | ||
60 | ||
61 | class User(Model): | |
62 | ||
63 | id = IntegerField('id') | |
64 | name = StringField('username') | |
65 | email = StringField('email') | |
66 | password = StringField('password') | |
67 | ||
68 | ||
69 | class SubUser(User): | |
70 | ||
71 | nickname = StringField('nickname') | |
72 | ||
73 | ||
74 | if __name__ == '__main__': | |
75 | ||
76 | u = User(id=123, name='Michael', email='test@orm.org', password='my-pwd') | |
77 | u.save() |