-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContextManager.py
72 lines (56 loc) · 1.42 KB
/
ContextManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from contextlib import contextmanager
class Connection:
def conn(self):
print("conn")
return "conn"
def close(self):
print("close")
def commit(self):
print("commit")
def rollback(self):
print("rollback")
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
self.rollback()
else:
self.commit()
self.close()
return True
def __enter__(self):
return self.conn()
@contextmanager
def conn():
try:
print("conn")
yield "conn"
print("commit")
except Exception:
print("rollback")
finally:
print("close")
connection = Connet = Connection
if __name__ == "__main__":
"""
模拟数据库操作场景,代码执行成功,则提交事务,否则回滚事务。
不管执行是否成功,最后关闭连接。
"""
# 传统方式,自己维护上下文
c = Connection()
try:
print("GET:", c.conn())
raise Exception
c.commit()
except Exception:
c.rollback()
finally:
c.close()
print("=" * 60)
# 定义Class进入和退出时的动作
with connection() as c:
print("GET:", c)
raise Exception
print("=" * 60)
# 使用contextlib包中封装好的@contextmanager进行上下文管理
with conn() as c:
print("GET:", c)
raise Exception