Refactor EventHandlerBase to be more general

This commit is contained in:
Kristóf Tóth 2018-04-18 20:07:41 +02:00
parent addd517ba7
commit 9d93d055b8

View File

@ -17,12 +17,15 @@ class EventHandlerBase(ABC):
def __init__(self, key): def __init__(self, key):
self.server_connector = ServerConnector() self.server_connector = ServerConnector()
self.key = key self.key = key
self.subscriptions = set() self.subscribe(self.key, 'reset')
self.subscribe(self.key)
self.subscribe('reset')
self.server_connector.register_callback(self.event_handler_callback) self.server_connector.register_callback(self.event_handler_callback)
def event_handler_callback(self, msg_parts): 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) message = deserialize_tfw_msg(*msg_parts)
response = self.dispatch_handling(message) response = self.dispatch_handling(message)
response['key'] = message['key'] response['key'] = message['key']
@ -37,31 +40,49 @@ class EventHandlerBase(ABC):
@abstractmethod @abstractmethod
def handle_event(self, message): def handle_event(self, message):
"""
Abstract method that implements the handling of messages.
:param message: the message received
"""
raise NotImplementedError raise NotImplementedError
def handle_reset(self, message): def handle_reset(self, message):
# pylint: disable=unused-argument,no-self-use # pylint: disable=unused-argument,no-self-use
"""
'reset' events usually receive some sort of special treatment.
:param message: the message received
"""
return None return None
def cleanup(self): def subscribe(self, *keys):
pass """
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): :param keys: list of keys to subscribe to
if key not in self.subscriptions: """
self.subscriptions.add(key) for key in keys:
self.server_connector.subscribe(key) self.server_connector.subscribe(key)
def unsubscribe(self, key): def unsubscribe(self, *keys):
try: """
self.subscriptions.remove(key) Unsubscribe this eventhandler from the given keys.
self.server_connector.unsubscribe(key)
except KeyError:
pass
def unsubscribe_all(self): :param keys: list of keys to unsubscribe from
for sub in self.subscriptions: """
self.server_connector.unsubscribe(key=sub) for key in keys:
self.subscriptions.clear() 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): class TriggeredEventHandler(EventHandlerBase, ABC):