mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-22 16:51:31 +00:00
Refactor EventHandlerBase to be more general
This commit is contained in:
parent
addd517ba7
commit
9d93d055b8
@ -17,12 +17,15 @@ class EventHandlerBase(ABC):
|
||||
def __init__(self, key):
|
||||
self.server_connector = ServerConnector()
|
||||
self.key = key
|
||||
self.subscriptions = set()
|
||||
self.subscribe(self.key)
|
||||
self.subscribe('reset')
|
||||
self.subscribe(self.key, 'reset')
|
||||
self.server_connector.register_callback(self.event_handler_callback)
|
||||
|
||||
def event_handler_callback(self, msg_parts):
|
||||
"""
|
||||
Callback that is invoked when receiving a message.
|
||||
This is subscribed in __init__().
|
||||
"""
|
||||
# TODO: fix faulty logic below
|
||||
message = deserialize_tfw_msg(*msg_parts)
|
||||
response = self.dispatch_handling(message)
|
||||
response['key'] = message['key']
|
||||
@ -37,31 +40,49 @@ class EventHandlerBase(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def handle_event(self, message):
|
||||
"""
|
||||
Abstract method that implements the handling of messages.
|
||||
|
||||
:param message: the message received
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def handle_reset(self, message):
|
||||
# pylint: disable=unused-argument,no-self-use
|
||||
"""
|
||||
'reset' events usually receive some sort of special treatment.
|
||||
|
||||
:param message: the message received
|
||||
"""
|
||||
return None
|
||||
|
||||
def cleanup(self):
|
||||
pass
|
||||
def subscribe(self, *keys):
|
||||
"""
|
||||
Subscribe this EventHandler to receive events for given keys.
|
||||
Note that you can subscribe to the same key several times in which
|
||||
case you will need to unsubscribe multiple times in order to stop
|
||||
receiving events.
|
||||
|
||||
def subscribe(self, key):
|
||||
if key not in self.subscriptions:
|
||||
self.subscriptions.add(key)
|
||||
:param keys: list of keys to subscribe to
|
||||
"""
|
||||
for key in keys:
|
||||
self.server_connector.subscribe(key)
|
||||
|
||||
def unsubscribe(self, key):
|
||||
try:
|
||||
self.subscriptions.remove(key)
|
||||
self.server_connector.unsubscribe(key)
|
||||
except KeyError:
|
||||
pass
|
||||
def unsubscribe(self, *keys):
|
||||
"""
|
||||
Unsubscribe this eventhandler from the given keys.
|
||||
|
||||
def unsubscribe_all(self):
|
||||
for sub in self.subscriptions:
|
||||
self.server_connector.unsubscribe(key=sub)
|
||||
self.subscriptions.clear()
|
||||
:param keys: list of keys to unsubscribe from
|
||||
"""
|
||||
for key in keys:
|
||||
self.server_connector.unsubscribe(key)
|
||||
|
||||
def cleanup(self):
|
||||
"""
|
||||
Perform cleanup actions such as releasing database
|
||||
connections and stuff like that.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class TriggeredEventHandler(EventHandlerBase, ABC):
|
||||
|
Loading…
Reference in New Issue
Block a user