Python Twisted JSON RPC

Alex Amato picture Alex Amato · Jan 19, 2011 · Viewed 14.8k times · Source

Can anyone recommend some simple code to set up a simple JSON RPC client and server using twisted?

I found txJSON-RPC, but I was wondering if someone had some experience using some of these anc could recommend something.

Answer

nosklo picture nosklo · Jan 19, 2011

txJSONRPC is great. I use it and it works. I suggest you give it a try.

SERVER:

from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor

class Math(jsonrpc.JSONRPC):
    """
    An example object to be published.
    """
    def jsonrpc_add(self, a, b):
        """
        Return sum of arguments.
        """
        return a + b

reactor.listenTCP(7080, server.Site(Math()))
reactor.run()

CLIENT:

from twisted.internet import reactor
from txjsonrpc.web.jsonrpc import Proxy

def printValue(value):
    print "Result: %s" % str(value)

def printError(error):
    print 'error', error

def shutDown(data):
    print "Shutting down reactor..."
    reactor.stop()

proxy = Proxy('http://127.0.0.1:7080/')

d = proxy.callRemote('add', 3, 5)
d.addCallback(printValue).addErrback(printError).addBoth(shutDown)
reactor.run()

As a bonus, I will leave some alternative: amp. http://amp-protocol.net