Python json-rpc

From wikinotes

The json-rpc library is entirely independent of any sockets/requests/webserver leaving you free to use it however/wherever it is useful to you. There is however some nifty builtin error-checking for http-specific issues like dropping connections, etc. There are instructions on the webpage for integrating with django, flask and other web frameworks.


JSON-RPC format

See json-rpc.



Components

dispatcher
jsonrpc.dispatcher.*
dict-like object that maps method_name to functions
manager
jsonrpc.JSONRPCResponseManager
handles JSONRPC validation, dropped connections, catches python exceptions...


dispatcher

from jsonrpc.dispatcher import Dispatcher

default_mapping = {
	"echo" : repeat,
	"help" : help,
}

dispatcher = Dispatcher( default_mapping )       ## dispatcher can be built with a default mapping
dispatcher.add_method( do_something, name='do' ) ## add a new mapping to the dispatcher

@dispatcher.add_method
def do_something_else(*args,**kwds):             ## you can also add new methods to the dispatcher automatically with
	pass                                          ## a decorator



manager

from jsonrpc import JSONRPCResponseManager
import requests

## when received from socket/webserver, the request will
## be a requests object encompassing a JSON request.
## ex:

request  = requests.Request(
	method = 'post',
	url    = '127.0.0.1',
	data   = json.dumps( {
					"jsonrpc": "2.0",
					"method" : "some_function",
					"id"     : 0
				}),
	...
	)

response = JSONRPCResponseManager.handle( request.data, dispatcher )     ## handle an individual request using a specific dispatcher
                                                                         ## response is a jsonrpc.jsonrpc2.JSONRPC20Response object

return requests.Response( response.json, mimetype='application/json' )   ## return it as a reqests.Response



exceptions

A very useful feature of this library is that all raised exceptions are wrapped in a JSONRPCServerError and returned to the sender. Unfortunately (possibly for security), this does not return information about the exception itself to the sender. (although I expect it would be trivial to implement this behaviour using a subclass...)

response = request.post( url, my_json, headers=headers )

if not response.ok:
	raise response.raise_for_status()


Custom errors (with their own JSONRPC error-codes) can be created by subclassing JSONRPCDispatchException.




Simple Example

server

client