用Metaclass实现一个精简的ORM框架详解编程语言

存档:

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

结果如下:

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]

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11960.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论