My favorites | Sign in
Project Logo
                
Code license: Apache License 2.0
Labels: json, rpc, python
People details
Project owners:
  catchjosh
Project committers:
yucetekol

Summary

This library implements the JSON-RPC 2.0 proposed specification in pure Python. It is designed to be as compatible with the syntax of xmlrpclib as possible (it extends where possible), so that projects using xmlrpclib could easily be modified to use JSON and experiment with the differences.

It is backwards-compatible with the 1.0 specification, and supports all of the new proposed features of 2.0, including:

Eventually, I'll tie in a SimpleJSONRPCServer library, with the purpose of mirroring the SimpleXMLRPCServer file. To test it with another library, you can use my TornadoRPC library for Tornado.

Requirements

It supports cjson and simplejson, and looks for the parsers in that order (searching first for cjson, then for the "built-in" simplejson (as json) in 2.6+, and then the simplejson external library. One of these must be installed to use this library, although if you have a standard distribution of 2.6+, you should already have one. Keep in mind that cjson is supposed to be the quickest, I believe, so if you are going for full-on optimization you may want to pick it up.

Usage

This is (obviously) taken from a console session.

>>> import jsonrpclib
>>> server = jsonrpclib.Server('http://localhost:8181')
>>> server.add(5,6)
11
>>> print jsonrpclib.history.request
{"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
>>> print jsonrpclib.history.response
{'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
>>> server.add(x=5, y=10)
15
>>> server._notify.add(5,6)
# No result returned...
>>> batch = jsonrpclib.MultiCall(server)
>>> batch.add(5, 6)
>>> batch.ping({'key':'value'})
>>> batch._notify.add(4, 30)
>>> results = batch()
>>> for result in results:
>>> ... print result
11
{'key': 'value'}
# Note that there are only two responses -- this is according to spec.

If you need 1.0 functionality, there are a bunch of places you can pass that in, although the best is just to change the value on jsonrpclib.config.version:

>>> import jsonrpclib
>>> jsonrpclib.config.version
2.0
>>> jsonrpclib.config.version = 1.0
>>> server = jsonrpclib.Server('http://localhost:8181')
>>> server.add(7, 10)
17
>>> print jsonrpclib..history.request
{"params": [7, 10], "id": "thes7tl2", "method": "add"}
>>> print jsonrpclib.history.response
{'id': 'thes7tl2', 'result': 17, 'error': None}
>>> 

The equivalent loads and dumps functions also exist, although with minor modifications. The dumps arguments are almost identical, but it adds three arguments: rpcid for the 'id' key, version to specify the JSON-RPC compatibility, and notify if it's a request that you want to be a notification. Additionally, the loads method does not return the params and method like xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and b.) returns the entire structure of the request / response for manual parsing.

Class Translation

I've recently added "automatic" class translation support. This can be devastatingly slow if improperly used, so the following is just a short list of things to keep in mind when using it.

[test_obj.py]
# This object is /very/ simple, and the system will look through the attributes
# and serialize what it can.
class TestObj(object):
    foo = 'bar'

# This object requires __init__ params, so it uses the _serialize method
# and returns a tuple of init params and attribute values (the init params
# can be a dict or a list, but the attribute values must be a dict.)
class TestSerial(object):
    foo = 'bar'
    def __init__(self, *args):
        self.args = args
    def _serialize(self):
        return (self.args, {'foo':self.foo,})

[usage]
import jsonrpclib
import test_obj

testobj1 = test_obj.TestObj()
testobj2 = test_obj.TestSerial()
server = jsonrpclib.Server('http://localhost:8080')
# The 'ping' just returns whatever is sent
ping1 = server.ping(testobj1)
ping2 = server.ping(testobj2)
print jsonrpclib.history.request
# {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
print jsonrpclib.histry.result
# {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}

To turn off this behaviour, just set jsonrpclib.config.use_jsonclass to False. If you want to use a different method for serialization, just set jsonrpclib.config.serialize_method to the method name. Finally, if you are using classes that you have defined in the implementation (as in, not a separate library), you'll need to add those (on BOTH the server and the client) using the jsonrpclib.config.classes.add() method. (Examples forthcoming.)

Feedback on this "feature" is very, VERY much appreciated.

SimpleJSONRPCServer

This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in usage are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different, since this is within the jsonrpclib library.

from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer

server = SimpleJSONRPCServer(('localhost', 8080))
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_function(lambda x: x, 'ping')
server.serve_forever()

This has not been tested exhaustively, so I'll keep updating with reports.

Why JSON-RPC?

In my opinion, there are three main reasons to choose JSON over XML for RPC:

There are also a few reasons to choose XML over JSON:

TODO


I invite all criticism, advice, patches, etc. although I request that politeness is always included. :)









Hosted by Google Code