--- /dev/null
+JSONRPClib
+==========
+This library is an implementation of the JSON-RPC specification.
+It supports both the original 1.0 specification, as well as the
+new (proposed) 2.0 spec, which includes batch submission, keyword
+arguments, etc.
+
+It is licensed under the Apache License, Version 2.0
+(http://www.apache.org/licenses/LICENSE-2.0.html).
+
+Communication
+-------------
+Feel free to send any questions, comments, or patches to our Google Group
+mailing list (you'll need to join to send a message):
+http://groups.google.com/group/jsonrpclib
+
+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:
+
+* Batch submission (via MultiCall)
+* Keyword arguments
+* Notifications (both in a batch and 'normal')
+* Class translation using the 'jsonclass' key.
+
+I've added a "SimpleJSONRPCServer", which is intended to emulate the
+"SimpleXMLRPCServer" from the default Python distribution.
+
+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.
+
+Client Usage
+------------
+
+This is (obviously) taken from a console session.
+
+<code>
+ >>> import jsonrpclib
+ >>> server = jsonrpclib.Server('http://localhost:8080')
+ >>> 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.
+</code>
+
+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:
+
+<code>
+ >>> import jsonrpclib
+ >>> jsonrpclib.config.version
+ 2.0
+ >>> jsonrpclib.config.version = 1.0
+ >>> server = jsonrpclib.Server('http://localhost:8080')
+ >>> 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}
+ >>>
+</code>
+
+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.
+
+SimpleJSONRPCServer
+-------------------
+This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in features are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different from the regular SimpleXMLRPCServer, since the SimpleJSONRPCServer is distributed within the jsonrpclib library.
+
+<code>
+ 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()
+</code>
+
+Class Translation
+-----------------
+I've recently added "automatic" class translation support, although it is
+turned off by default. 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.
+
+* Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
+* Do not require init params (for exceptions, keep reading)
+* Getter properties without setters could be dangerous (read: not tested)
+
+If any of the above are issues, use the _serialize method. (see usage below)
+The server and client must BOTH have use_jsonclass configuration item on and
+they must both have access to the same libraries used by the objects for
+this to work.
+
+If you have excessively nested arguments, it would be better to turn off the
+translation and manually invoke it on specific objects using
+jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default
+behavior recursively goes through attributes and lists / dicts / tuples).
+
+[test_obj.py]
+
+<code>
+ # 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,})
+</code>
+
+[usage]
+
+<code>
+ import jsonrpclib
+ import test_obj
+
+ jsonrpclib.config.use_jsonclass = True
+
+ 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.history.result
+ # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
+</code>
+
+To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True.
+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.
+
+Why JSON-RPC?
+-------------
+In my opinion, there are several reasons to choose JSON over XML for RPC:
+
+* Much simpler to read (I suppose this is opinion, but I know I'm right. :)
+* Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
+* Parsing - JSON should be much quicker to parse than XML.
+* Easy class passing with jsonclass (when enabled)
+
+In the interest of being fair, there are also a few reasons to choose XML
+over JSON:
+
+* Your server doesn't do JSON (rather obvious)
+* Wider XML-RPC support across APIs (can we change this? :))
+* Libraries are more established, i.e. more stable (Let's change this too.)
+
+TESTS
+-----
+I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
+You can run it with:
+
+ python tests.py
+
+TODO
+----
+* Use HTTP error codes on SimpleJSONRPCServer
+* Test, test, test and optimize
\ No newline at end of file
--- /dev/null
+"""
+The tests in this file compare the request and response objects
+to the JSON-RPC 2.0 specification document, as well as testing
+several internal components of the jsonrpclib library. Run this
+module without any parameters to run the tests.
+
+Currently, this is not easily tested with a framework like
+nosetests because we spin up a daemon thread running the
+the Server, and nosetests (at least in my tests) does not
+ever "kill" the thread.
+
+If you are testing jsonrpclib and the module doesn't return to
+the command prompt after running the tests, you can hit
+"Ctrl-C" (or "Ctrl-Break" on Windows) and that should kill it.
+
+TODO:
+* Finish implementing JSON-RPC 2.0 Spec tests
+* Implement JSON-RPC 1.0 tests
+* Implement JSONClass, History, Config tests
+"""
+
+from jsonrpclib import Server, MultiCall, history, config, ProtocolError
+from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
+from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCRequestHandler
+import unittest
+import os
+try:
+ import json
+except ImportError:
+ import simplejson as json
+from threading import Thread
+
+PORTS = range(8000, 8999)
+
+class TestCompatibility(unittest.TestCase):
+
+ client = None
+ port = None
+ server = None
+
+ def setUp(self):
+ self.port = PORTS.pop()
+ self.server = server_set_up(port=self.port)
+ self.client = Server('http://localhost:%d' % self.port)
+
+ # v1 tests forthcoming
+
+ # Version 2.0 Tests
+ def test_positional(self):
+ """ Positional arguments in a single call """
+ result = self.client.subtract(23, 42)
+ self.assertTrue(result == -19)
+ result = self.client.subtract(42, 23)
+ self.assertTrue(result == 19)
+ request = json.loads(history.request)
+ response = json.loads(history.response)
+ verify_request = {
+ "jsonrpc": "2.0", "method": "subtract",
+ "params": [42, 23], "id": request['id']
+ }
+ verify_response = {
+ "jsonrpc": "2.0", "result": 19, "id": request['id']
+ }
+ self.assertTrue(request == verify_request)
+ self.assertTrue(response == verify_response)
+
+ def test_named(self):
+ """ Named arguments in a single call """
+ result = self.client.subtract(subtrahend=23, minuend=42)
+ self.assertTrue(result == 19)
+ result = self.client.subtract(minuend=42, subtrahend=23)
+ self.assertTrue(result == 19)
+ request = json.loads(history.request)
+ response = json.loads(history.response)
+ verify_request = {
+ "jsonrpc": "2.0", "method": "subtract",
+ "params": {"subtrahend": 23, "minuend": 42},
+ "id": request['id']
+ }
+ verify_response = {
+ "jsonrpc": "2.0", "result": 19, "id": request['id']
+ }
+ self.assertTrue(request == verify_request)
+ self.assertTrue(response == verify_response)
+
+ def test_notification(self):
+ """ Testing a notification (response should be null) """
+ result = self.client._notify.update(1, 2, 3, 4, 5)
+ self.assertTrue(result == None)
+ request = json.loads(history.request)
+ response = history.response
+ verify_request = {
+ "jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]
+ }
+ verify_response = ''
+ self.assertTrue(request == verify_request)
+ self.assertTrue(response == verify_response)
+
+ def test_non_existent_method(self):
+ self.assertRaises(ProtocolError, self.client.foobar)
+ request = json.loads(history.request)
+ response = json.loads(history.response)
+ verify_request = {
+ "jsonrpc": "2.0", "method": "foobar", "id": request['id']
+ }
+ verify_response = {
+ "jsonrpc": "2.0",
+ "error":
+ {"code": -32601, "message": response['error']['message']},
+ "id": request['id']
+ }
+ self.assertTrue(request == verify_request)
+ self.assertTrue(response == verify_response)
+
+ def test_invalid_json(self):
+ invalid_json = '{"jsonrpc": "2.0", "method": "foobar, '+ \
+ '"params": "bar", "baz]'
+ response = self.client._run_request(invalid_json)
+ response = json.loads(history.response)
+ verify_response = json.loads(
+ '{"jsonrpc": "2.0", "error": {"code": -32700,'+
+ ' "message": "Parse error."}, "id": null}'
+ )
+ verify_response['error']['message'] = response['error']['message']
+ self.assertTrue(response == verify_response)
+
+ def test_invalid_request(self):
+ invalid_request = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}'
+ response = self.client._run_request(invalid_request)
+ response = json.loads(history.response)
+ verify_response = json.loads(
+ '{"jsonrpc": "2.0", "error": {"code": -32600, '+
+ '"message": "Invalid Request."}, "id": null}'
+ )
+ verify_response['error']['message'] = response['error']['message']
+ self.assertTrue(response == verify_response)
+
+ def test_batch_invalid_json(self):
+ invalid_request = '[ {"jsonrpc": "2.0", "method": "sum", '+ \
+ '"params": [1,2,4], "id": "1"},{"jsonrpc": "2.0", "method" ]'
+ response = self.client._run_request(invalid_request)
+ response = json.loads(history.response)
+ verify_response = json.loads(
+ '{"jsonrpc": "2.0", "error": {"code": -32700,'+
+ '"message": "Parse error."}, "id": null}'
+ )
+ verify_response['error']['message'] = response['error']['message']
+ self.assertTrue(response == verify_response)
+
+ def test_empty_array(self):
+ invalid_request = '[]'
+ response = self.client._run_request(invalid_request)
+ response = json.loads(history.response)
+ verify_response = json.loads(
+ '{"jsonrpc": "2.0", "error": {"code": -32600, '+
+ '"message": "Invalid Request."}, "id": null}'
+ )
+ verify_response['error']['message'] = response['error']['message']
+ self.assertTrue(response == verify_response)
+
+ def test_nonempty_array(self):
+ invalid_request = '[1,2]'
+ request_obj = json.loads(invalid_request)
+ response = self.client._run_request(invalid_request)
+ response = json.loads(history.response)
+ self.assertTrue(len(response) == len(request_obj))
+ for resp in response:
+ verify_resp = json.loads(
+ '{"jsonrpc": "2.0", "error": {"code": -32600, '+
+ '"message": "Invalid Request."}, "id": null}'
+ )
+ verify_resp['error']['message'] = resp['error']['message']
+ self.assertTrue(resp == verify_resp)
+
+ def test_batch(self):
+ multicall = MultiCall(self.client)
+ multicall.sum(1,2,4)
+ multicall._notify.notify_hello(7)
+ multicall.subtract(42,23)
+ multicall.foo.get(name='myself')
+ multicall.get_data()
+ job_requests = [j.request() for j in multicall._job_list]
+ job_requests.insert(3, '{"foo": "boo"}')
+ json_requests = '[%s]' % ','.join(job_requests)
+ requests = json.loads(json_requests)
+ responses = self.client._run_request(json_requests)
+
+ verify_requests = json.loads("""[
+ {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
+ {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
+ {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
+ {"foo": "boo"},
+ {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
+ {"jsonrpc": "2.0", "method": "get_data", "id": "9"}
+ ]""")
+
+ # Thankfully, these are in order so testing is pretty simple.
+ verify_responses = json.loads("""[
+ {"jsonrpc": "2.0", "result": 7, "id": "1"},
+ {"jsonrpc": "2.0", "result": 19, "id": "2"},
+ {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
+ {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "5"},
+ {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
+ ]""")
+
+ self.assertTrue(len(requests) == len(verify_requests))
+ self.assertTrue(len(responses) == len(verify_responses))
+
+ responses_by_id = {}
+ response_i = 0
+
+ for i in range(len(requests)):
+ verify_request = verify_requests[i]
+ request = requests[i]
+ response = None
+ if request.get('method') != 'notify_hello':
+ req_id = request.get('id')
+ if verify_request.has_key('id'):
+ verify_request['id'] = req_id
+ verify_response = verify_responses[response_i]
+ verify_response['id'] = req_id
+ responses_by_id[req_id] = verify_response
+ response_i += 1
+ response = verify_response
+ self.assertTrue(request == verify_request)
+
+ for response in responses:
+ verify_response = responses_by_id.get(response.get('id'))
+ if verify_response.has_key('error'):
+ verify_response['error']['message'] = \
+ response['error']['message']
+ self.assertTrue(response == verify_response)
+
+ def test_batch_notifications(self):
+ multicall = MultiCall(self.client)
+ multicall._notify.notify_sum(1, 2, 4)
+ multicall._notify.notify_hello(7)
+ result = multicall()
+ self.assertTrue(len(result) == 0)
+ valid_request = json.loads(
+ '[{"jsonrpc": "2.0", "method": "notify_sum", '+
+ '"params": [1,2,4]},{"jsonrpc": "2.0", '+
+ '"method": "notify_hello", "params": [7]}]'
+ )
+ request = json.loads(history.request)
+ self.assertTrue(len(request) == len(valid_request))
+ for i in range(len(request)):
+ req = request[i]
+ valid_req = valid_request[i]
+ self.assertTrue(req == valid_req)
+ self.assertTrue(history.response == '')
+
+class InternalTests(unittest.TestCase):
+ """
+ These tests verify that the client and server portions of
+ jsonrpclib talk to each other properly.
+ """
+ client = None
+ server = None
+ port = None
+
+ def setUp(self):
+ self.port = PORTS.pop()
+ self.server = server_set_up(port=self.port)
+
+ def get_client(self):
+ return Server('http://localhost:%d' % self.port)
+
+ def get_multicall_client(self):
+ server = self.get_client()
+ return MultiCall(server)
+
+ def test_connect(self):
+ client = self.get_client()
+ result = client.ping()
+ self.assertTrue(result)
+
+ def test_single_args(self):
+ client = self.get_client()
+ result = client.add(5, 10)
+ self.assertTrue(result == 15)
+
+ def test_single_kwargs(self):
+ client = self.get_client()
+ result = client.add(x=5, y=10)
+ self.assertTrue(result == 15)
+
+ def test_single_kwargs_and_args(self):
+ client = self.get_client()
+ self.assertRaises(ProtocolError, client.add, (5,), {'y':10})
+
+ def test_single_notify(self):
+ client = self.get_client()
+ result = client._notify.add(5, 10)
+ self.assertTrue(result == None)
+
+ def test_single_namespace(self):
+ client = self.get_client()
+ response = client.namespace.sum(1,2,4)
+ request = json.loads(history.request)
+ response = json.loads(history.response)
+ verify_request = {
+ "jsonrpc": "2.0", "params": [1, 2, 4],
+ "id": "5", "method": "namespace.sum"
+ }
+ verify_response = {
+ "jsonrpc": "2.0", "result": 7, "id": "5"
+ }
+ verify_request['id'] = request['id']
+ verify_response['id'] = request['id']
+ self.assertTrue(verify_request == request)
+ self.assertTrue(verify_response == response)
+
+ def test_multicall_success(self):
+ multicall = self.get_multicall_client()
+ multicall.ping()
+ multicall.add(5, 10)
+ multicall.namespace.sum([5, 10, 15])
+ correct = [True, 15, 30]
+ i = 0
+ for result in multicall():
+ self.assertTrue(result == correct[i])
+ i += 1
+
+ def test_multicall_success(self):
+ multicall = self.get_multicall_client()
+ for i in range(3):
+ multicall.add(5, i)
+ result = multicall()
+ self.assertTrue(result[2] == 7)
+
+ def test_multicall_failure(self):
+ multicall = self.get_multicall_client()
+ multicall.ping()
+ multicall.add(x=5, y=10, z=10)
+ raises = [None, ProtocolError]
+ result = multicall()
+ for i in range(2):
+ if not raises[i]:
+ result[i]
+ else:
+ def func():
+ return result[i]
+ self.assertRaises(raises[i], func)
+
+
+""" Test Methods """
+def subtract(minuend, subtrahend):
+ """ Using the keywords from the JSON-RPC v2 doc """
+ return minuend-subtrahend
+
+def add(x, y):
+ return x + y
+
+def update(*args):
+ return args
+
+def summation(*args):
+ return sum(args)
+
+def notify_hello(*args):
+ return args
+
+def get_data():
+ return ['hello', 5]
+
+def ping():
+ return True
+
+def server_set_up(port):
+ # Not sure this is a good idea to spin up a new server thread
+ # for each test... but it seems to work fine.
+ def log_request(self, *args, **kwargs):
+ """ Making the server output 'quiet' """
+ pass
+ SimpleJSONRPCRequestHandler.log_request = log_request
+ server = SimpleJSONRPCServer(('', port))
+ server.register_function(summation, 'sum')
+ server.register_function(summation, 'notify_sum')
+ server.register_function(notify_hello)
+ server.register_function(subtract)
+ server.register_function(update)
+ server.register_function(get_data)
+ server.register_function(add)
+ server.register_function(ping)
+ server.register_function(summation, 'namespace.sum')
+ server_proc = Thread(target=server.serve_forever)
+ server_proc.daemon = True
+ server_proc.start()
+ return server_proc
+
+if __name__ == '__main__':
+ unittest.main()
+