Commits

Stefan Scherfke  committed 828a1d4

Addes MessageHandler base class.

  • Participants
  • Parent commits a678ab7

Comments (0)

Files changed (1)

File example_app/base.py

 import multiprocessing
 
 from zmq.eventloop import ioloop, zmqstream
+from zmq.utils import jsonapi as json
 import zmq
 
 
             stream.on_recv(callback)
 
         return stream, int(port)
+
+
+class MessageHandler(object):
+    """
+    Base class for message handlers for a :class:`ZMQProcess`.
+
+    Inheriting classes only need to implement a handler function for each
+    message type.
+
+    """
+    def __init__(self, logger, stream_name, json_load=-1):
+        self._logger = logger
+        self._stream_name = stream_name
+        self._json_load = json_load
+        self._argspec_cache = {}
+
+    def __call__(self, msg):
+        """
+        Gets called when a messages is received by the stream this handlers is
+        registered at. *msg* is a list as return by
+        :meth:`zmq.core.socket.Socket.recv_multipart`.
+
+        """
+        self._logger.debug('%s stream received: %s' % (self._stream_name, msg))
+
+        # Try to JSON-decode the index "self._json_load" of the message
+        i = self._json_load
+        msg_type, data = json.loads(msg[i])
+        msg[i] = data
+
+        # Get the actual message handler and call it
+        if msg_type.startswith('_'):
+            raise AttributeError('%s starts with an "_"' % msg_type)
+
+        getattr(self, msg_type)(*msg)