Sunday, May 07, 2006

Twisted JSON-RPC TCP Proxy and Server

twisted :: python :: internet






Yesterday I finished the Twisted JSON-RPC server and proxy for TCP. I
decided to go with the
Netstring protocol
for its simplicity and the security of declaring and limiting string
length.

Usage is very simple and almost identical to the HTTP-based Twisted
JSON-RPC usage. Here is some server code:


from twisted.application import service, internet

from adytum.twisted import jsonrpc

class Example(jsonrpc.JSONRPC):
"""An example object to be published."""

def jsonrpc_echo(self, x):
"""Return all passed args."""
return x

factory = jsonrpc.RPCFactory(Example)
application = service.Application("Example JSON-RPC Server")
jsonrpcServer = internet.TCPServer(7080, factory)
jsonrpcServer.setServiceParent(application)


And for the client:

from twisted.internet import reactor
from twisted.internet import defer

from adytum.twisted.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()

print "Making remote calls..."
proxy = Proxy('127.0.0.1', 7080)

d = proxy.callRemote('echo', 'hey!')
d.addCallbacks(printValue, printError)
d.addCallback(shutDown)
reactor.run()

For a slightly more complex example (with subhandlers and
introspection) see:
the wiki.

Next on the list? For a truly secure solution, I am exploring the use
of the
Twisted
Perspective Broker
for JSON-RPC.


Now playing:
Yoko Kanno & The Seatbelts - Forever Broke

Friday, May 05, 2006

More Twisted and JSON-RPC

twisted :: python :: web






A recent comment on my
Twisted
JSON-RPC blog entry

put this near the top of my queue. I posted a comment in response to
the request for a download link (see my
comments
about that).

Please read those comments before downloading this, so you are aware of
the connection (or lack thereof) to official twisted code, as well as
my reservations on the matter. In addition to providing this link, I
will do the following: create a twisted.web2 version of the JSON-RPC
code this weekend, make an attempt to define a sensible twisted
protocol for JSON-RPC over TCP, and (time-permitting) begin work on a
twisted TCP JSON-RPC server and client. I have created a project space
for this work
here.

Update: There is now a twisted.web2 version of the JSON-RPC server available on the project page (all unit tests pass). There is an example server.tac file you can run as well as an example twisted client. Some time later tonight -- or rather, very early this morning (2006.05.06) -- I will put some eggs up and provide a link on the project page.




Now playing:
Glenn Gould - The Art of Fugue, BWV 1080: Contrapunctus XI (a 4)