forked from tom-kerr/bookmaker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.py
91 lines (80 loc) · 2.71 KB
/
events.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class OnEvents(object):
""" """
def __init__(self):
self.success_hooks = []
self.failure_hooks = []
self.exit_hooks = []
def on_success(self, *args, **kwargs):
pass
def call_success_hooks(self, *args, **kwargs):
while self.success_hooks:
hook = self.success_hooks.pop()
hook(*args, **kwargs)
def on_failure(self, *args, exception=None, **kwargs):
runtimeerror = RuntimeError('An error occurred executing ' +
self.__class__.__name__)
if exception:
raise runtimeerror from exception
else:
raise runtimeerror
def call_failure_hooks(self, *args, **kwargs):
while self.failure_hooks:
hook = self.failure_hooks.pop()
hook(*args, **kwargs)
def on_exit(self, *args, **kwargs):
pass
def call_exit_hooks(self, *args, **kwargs):
while self.exit_hooks:
hook = self.exit_hooks.pop()
hook(*args, **kwargs)
def event_trigger(self, event, *args, **kwargs):
try:
if event == True:
try:
self.on_success(*args, **kwargs)
except (Exception, BaseException):
raise
finally:
self.call_success_hooks(*args, **kwargs)
elif event == False:
try:
self.call_failure_hooks(*args, **kwargs)
except (Exception, BaseException):
raise
finally:
self.on_failure(*args, **kwargs)
except:
raise
finally:
try:
self.on_exit(*args, **kwargs)
except (Exception, BaseException):
raise
finally:
self.call_exit_hooks(*args, **kwargs)
def handle_events(f):
def on_event(self, *args, **kwargs):
try:
f(self, *args, **kwargs)
except (Exception, BaseException) as e:
try:
self.call_failure_hooks(*args, **kwargs)
except (Exception, BaseException):
raise
finally:
self.on_failure(*args, exception=e, **kwargs)
else:
try:
self.on_success(*args, **kwargs)
except (Exception, BaseException):
raise
finally:
self.call_success_hooks(*args, **kwargs)
finally:
try:
self.on_exit(*args, **kwargs)
except (Exception, BaseException):
raise
finally:
self.call_exit_hooks(*args, **kwargs)
return on_event