Python Twisted JSON RPC

2019-01-16 19:53发布

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.

5条回答
该账号已被封号
2楼-- · 2019-01-16 20:29

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)))
查看更多
再贱就再见
3楼-- · 2019-01-16 20:31

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

查看更多
神经病院院长
4楼-- · 2019-01-16 20:31

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.

查看更多
祖国的老花朵
5楼-- · 2019-01-16 20:40

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.

查看更多
叼着烟拽天下
6楼-- · 2019-01-16 20:47

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

查看更多
登录 后发表回答