Python Twisted JSON RPC

2019-01-16 20:01发布

问题:

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.

回答1:

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



回答2:

If you are looking for a framework-independent approach, this lib I pushed (using mixin) might be helpful:



回答3:

Cyclone, a Tornado async web server implementation written using twisted, has a built-in json-rpc request handler that uses the python json/simplejson module. Example server and client code is here.



回答4:

wikipedia has a bunch of implementations listed for python: https://en.wikipedia.org/wiki/JSON-RPC#Implementations

That said, txjason feels like the one best integrated with twisted. It seems to support out of order responses out of the box for example. Most of it would be portable to python3 using six. The most horrible part is the parameter validation, which is not exposed in the normal public API anyway.



回答5:

For me this worked better then "libraries" , speaking of client.

    TESTDATA = {'id': 1234,
                'method': 'getbalance',
                }
    URL = 'http://localhost:7777'

    d= getPage(URL,method="POST",postdata=json.dumps(TESTDATA))
    d.addBoth(lambda x :print(json.loads(x)))