X-Git-Url: https://git.llucax.com/software/pymin.git/blobdiff_plain/fbb90886873a6430d44ba2c9e1cfc8ab9d7f14c4..92f311f91952623a83b6cb5c31f6e3c7c052df16:/pymindaemon.py?ds=inline diff --git a/pymindaemon.py b/pymindaemon.py index 1ddef6c..98ced48 100644 --- a/pymindaemon.py +++ b/pymindaemon.py @@ -10,10 +10,12 @@ command-line. import signal import socket -from dispatcher import Dispatcher -from eventloop import EventLoop, LoopInterruptedError -class PyminDaemon(EventLoop): +import dispatcher +import eventloop +import serializer + +class PyminDaemon(eventloop.EventLoop): r"""PyminDaemon(bind_addr, routes) -> PyminDaemon instance This class is well suited to run as a single process. It handles @@ -41,9 +43,9 @@ class PyminDaemon(EventLoop): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(bind_addr) # Create EventLoop - EventLoop.__init__(self, sock) + eventloop.EventLoop.__init__(self, sock) # Create Dispatcher - self.dispatcher = Dispatcher(routes) + self.dispatcher = dispatcher.Dispatcher(routes) # Signal handling def quit(signum, frame): print "Shuting down ..." @@ -58,31 +60,39 @@ class PyminDaemon(EventLoop): def handle(self): r"handle() -> None :: Handle incoming events using the dispatcher." (msg, addr) = self.file.recvfrom(65535) - result = self.dispatcher.dispatch(msg) + try: + result = self.dispatcher.dispatch(msg) + if result is not None: + result = serializer.serialize(result) + response = u'OK ' + except Exception, e: + result = unicode(e) + response = u'ERROR ' if result is None: - msg = 'OK 0' + response += u'0' else: - msg = 'OK %d\n%s' % (len(str(result)), result) - self.file.sendto(msg, addr) - #try: - # d.dispatch(msg) - #except dis.BadRouteError, inst: - # sock.sendto('Bad route from : ' + inst.cmd + '\n', addr) - #except dis.CommandNotFoundError, inst: - # sock.sendto('Command not found : ' + inst.cmd + '\n', addr) + response += u'%d\n%s' % (len(result), result) + self.file.sendto(response, addr) def run(self): r"run() -> None :: Run the event loop (shortcut to loop())" try: return self.loop() - except LoopInterruptedError, e: + except eventloop.LoopInterruptedError, e: pass if __name__ == '__main__': + from dispatcher import handler + @handler def test_handler(*args): print 'test:', args - PyminDaemon(('', 9999), dict(test=test_handler)).run() + @handler + def echo_handler(message): + print 'echo:', message + return message + + PyminDaemon(('', 9999), dict(test=test_handler, echo=echo_handler)).run()