Package: jsonrpclib-pelix
JSONRPClib (patched for Pelix and Python 3)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 specification, which includes batch submission, keyword
arguments, etc.This library is licensed under the terms of theApache Software License 2.0.About this versionThis is a patched version of the originaljsonrpclibproject by Josh Marshall,
available atjoshmarshall/jsonrpclib.The suffix-pelixonly indicates that this version works with Pelix
Remote Services, but it isnota Pelix specific implementation.This version adds support for Python 3, staying compatible with Python 2.7.
The support for Python 2.6 has been dropped, as it was becoming to hard to
maintain.It is now possible to use thedispatch_methodargument while extending theSimpleJSONRPCDispatcher, to use a custom dispatcher.
This allows to use this package by Pelix Remote Services.It can use thread pools to control the number of threads spawned to handle
notification requests and clients connections.The modifications added in other forks of this project have been added:Fromdrdaeman/jsonrpclib:Improved JSON-RPC 1.0 supportLess strict error response handlingFromtuomassalo/jsonrpclib:In case of a non-predefined error, raise an AppError and give access
toerror.dataFromdejw/jsonrpclib:Custom headers can be sent with request and associated testsSince version 0.4, this package added back the support of Unix sockets.This package cannot be installed with the originaljsonrpclib, as it uses
the same name.SummaryThis library implements the JSON-RPC 2.0 proposed specification in pure Python.
It is designed to be as compatible with the syntax ofxmlrpclibas possible
(it extends where possible), so that projects usingxmlrpclibcould 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 theMultiCallclass)Keyword argumentsNotifications (both in a batch and 'normal')Class translation using the__jsonclass__key.ASimpleJSONRPCServerclass has been added. It is intended to emulate theSimpleXMLRPCServerfrom the default Python distribution.RequirementsThis library supportsujson,cjsonandsimplejson, and looks for the
parsers in that order (searching first forujson,cjson,simplejsonand finally for thebuilt-injson).
One of these must be installed to use this library, although if you have a
standard distribution of 2.7+, you should already have one.
Keep in mind thatujsonis supposed to be the quickest, I believe, so if you
are going for full-on optimization you may want to pick it up.InstallationYou can install this from PyPI with one of the following commands (sudomight be required):# Global installation
pip install jsonrpclib-pelix

# Local installation
pip install --user jsonrpclib-pelixAlternatively, you can download the source from the GitHub repository attcalmant/jsonrpcliband manually
install it with the following commands:git clone git://github.com/tcalmant/jsonrpclib.git
cd jsonrpclib
python setup.py installA note on loggingjsonrpclib-pelixuses theloggingmodule from the standard Python
library to trace warnings and errors, but doesn't set it up.
As a result, you have to configure the Python logging to print out traces.The easiest way to do it is to add those lines at the beginning of your code:importlogginglogging.basiConfig()More information can be found in theloggingdocumentation page.SimpleJSONRPCServerThis is identical in usage (or should be) to theSimpleXMLRPCServerin the
Python standard library.
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 regularSimpleXMLRPCServer, since theSimpleJSONRPCServeris provided by thjsonrpcliblibrary.fromjsonrpclib.SimpleJSONRPCServerimportSimpleJSONRPCServerserver=SimpleJSONRPCServer(('localhost',8080))server.register_function(pow)server.register_function(lambdax,y:x+y,'add')server.register_function(lambdax:x,'ping')server.serve_forever()To start protect the server with SSL, use the following snippet:fromjsonrpclib.SimpleJSONRPCServerimportSimpleJSONRPCServerimportssl# Setup the SSL socketserver=SimpleJSONRPCServer(('localhost',8080),bind_and_activate=False)server.socket=ssl.wrap_socket(server.socket,certfile='server.pem',server_side=True)server.server_bind()server.server_activate()# ... register functions# Start the serverserver.serve_forever()Notification Thread PoolBy default, notification calls are handled in the request handling thread.
It is possible to use a thread pool to handle them, by giving it to the server
using theset_notification_pool()method:fromjsonrpclib.SimpleJSONRPCServerimportSimpleJSONRPCServerfromjsonrpclib.threadpoolimportThreadPool# Setup the thread pool: between 0 and 10 threadspool=ThreadPool(max_threads=10,min_threads=0)# Don't forget to start itpool.start()# Setup the serverserver=SimpleJSONRPCServer(('localhost',8080))server.set_notification_pool(pool)# Register methodsserver.register_function(pow)server.register_function(lambdax,y:x+y,'add')server.register_function(lambdax:x,'ping')try:server.serve_forever()finally:# Stop the thread pool (let threads finish their current task)pool.stop()server.set_notification_pool(None)Threaded serverIt is also possible to use a thread pool to handle clients requests, using thePooledJSONRPCServerclass.
By default, this class uses pool of 0 to 30 threads.
A custom pool can be given with thethread_poolparameter of the class
constructor.The notification pool and the request pool are different: by default, a server
with a request pool doesn't have a notification pool.fromjsonrpclib.SimpleJSONRPCServerimportPooledJSONRPCServerfromjsonrpclib.threadpoolimportThreadPool# Setup the notification and request poolsnofif_pool=ThreadPool(max_threads=10,min_threads=0)request_pool=ThreadPool(max_threads=50,min_threads=10)# Don't forget to start themnofif_pool.start()request_pool.start()# Setup the serverserver=PooledJSONRPCServer(('localhost',8080),thread_pool=request_pool)server.set_notification_pool(nofif_pool)# Register methodsserver.register_function(pow)server.register_function(lambdax,y:x+y,'add')server.register_function(lambdax:x,'ping')try:server.serve_forever()finally:# Stop the thread pools (let threads finish their current task)request_pool.stop()nofif_pool.stop()server.set_notification_pool(None)Unix socketTo start a server listening on a Unix socket, you will have to use the
following snippet:fromjsonrpclib.SimpleJSONRPCServerimportSimpleJSONRPCServerimportosimportsocket# Set the path to the socket filesocket_name="/tmp/my_socket.socket"# Ensure that the file doesn't exist yet (or an error will be raised)ifos.path.exists(socket_name):os.remove(socket_name)try:# Start the server, indicating the socket family# The server will force some flags when in Unix socket mode# (no log request, no reuse address, ...)srv=SimpleJSONRPCServer(socket_name,address_family=socket.AF_UNIX)# ... register methods to the server# Run the serversrv.serve_forever()exceptKeyboardInterrupt:# Shutdown the server gracefullysrv.shutdown()srv.server_close()finally:# You should clean up after the server stoppedos.remove(socket_name)This feature is tested on Linux during Travis-CI builds. It also has
been tested on Windows Subsystem for Linux (WSL) on Windows 10 1809.This feature is not available on "pure" Windows, as it doesn't provide
theAF_UNIXaddress family.Client UsageThis is (obviously) taken from a console session.>>>importjsonrpclib>>>server=jsonrpclib.ServerProxy('http://localhost:8080')>>>server.add(5,6)11>>>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()>>>forresultinresults:>>>...print(result)11{'key':'value'}# Note that there are only two responses -- this is according to spec.# Clean up>>>server('close')()# Using client history>>>history=jsonrpclib.history.History()>>>server=jsonrpclib.ServerProxy('http://localhost:8080',history=history)>>>server.add(5,6)11>>>print(history.request){"id":"f682b956-c8e1-4506-9db4-29fe8bc9fcaa","jsonrpc":"2.0","method":"add","params":[5,6]}>>>print(history.response){"id":"f682b956-c8e1-4506-9db4-29fe8bc9fcaa","jsonrpc":"2.0","result":11}# Clean up>>>server('close')()If you need 1.0 functionality, there are a bunch of places you can pass
that in, although the best is just to give a specific configuration tojsonrpclib.ServerProxy:>>>importjsonrpclib>>>jsonrpclib.config.DEFAULT.version2.0>>>config=jsonrpclib.config.Config(version=1.0)>>>history=jsonrpclib.history.History()>>>server=jsonrpclib.ServerProxy('http://localhost:8080',config=config,history=history)>>>server.add(7,10)17>>>print(history.request){"id":"827b2923-5b37-49a5-8b36-e73920a16d32","method":"add","params":[7,10]}>>>print(history.response){"id":"827b2923-5b37-49a5-8b36-e73920a16d32","error":null,"result":17}>>>server('close')()The equivalentloadsanddumpsfunctions also exist, although with
minor modifications.
Thedumpsarguments are almost identical, but it adds three arguments:rpcidfor theidkey,versionto specify the JSON-RPC compatibility,
andnotifyif it's a request that you want to be a notification.Additionally, theloadsmethod does not return the params and method likexmlrpclib, but instead
a.) parses for errors, raising ProtocolErrors, and
b.) returns the entire structure of the request / response for manual parsing.Unix socketsTo connect a JSON-RPC server over a Unix socket, you have to use a specific
protocol:unix+http.When connecting to a Unix socket in the current working directory, you can use
the following syntax:unix+http://my.socketWhen you need to give an absolute path you must use the path part of the URL,
the host part will be ignored. For example, you can use this URL to indicate a
Unix socket in/var/lib/daemon.socket:unix+http://./var/lib/daemon.socketNote:Currently, only HTTP is supported over a Unix socket.
If you want HTTPS support to be implemented, please create anissue on GitHubAdditional headersIf your remote service requires custom headers in request, you can pass them
using theheaderskeyword argument, when creating theServerProxy:>>>importjsonrpclib>>>server=jsonrpclib.ServerProxy("http://localhost:8080",headers={'X-Test':'Test'})You can also put additional request headers only for certain method
invocation:>>>importjsonrpclib>>>server=jsonrpclib.Server("http://localhost:8080")>>>withserver._additional_headers({'X-Test':'Test'})astest_server:...test_server.ping(42)...>>># X-Test header will be no longer sent in requestsOf course_additional_headerscontexts can be nested as well.Class TranslationThe library supports an"automatic"class translation process, 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_serializemethod (see usage below).
The server and client mustBOTHhave theuse_jsonclassconfiguration
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 usingjsonrpclib.jsonclass.dump/jsonrpclib.jsonclass.load(since the
default behavior recursively goes through attributes and lists/dicts/tuples).Sample file:test_obj.py# This object is /very/ simple, and the system will look through the# attributes and serialize what it can.classTestObj(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.)classTestSerial(object):foo='bar'def__init__(self,*args):self.args=argsdef_serialize(self):return(self.args,{'foo':self.foo,})Sample usage:>>>importjsonrpclib>>>importtest_obj# History is used only to print the serialized form of beans>>>history=jsonrpclib.history.History()>>>testobj1=test_obj.TestObj()>>>testobj2=test_obj.TestSerial()>>>server=jsonrpclib.Server('http://localhost:8080',history=history)# The 'ping' just returns whatever is sent>>>ping1=server.ping(testobj1)>>>ping2=server.ping(testobj2)>>>print(history.request){"id":"7805f1f9-9abd-49c6-81dc-dbd47229fe13","jsonrpc":"2.0","method":"ping","params":[{"__jsonclass__":["test_obj.TestSerial",[]],"foo":"bar"}]}>>>print(history.response){"id":"7805f1f9-9abd-49c6-81dc-dbd47229fe13","jsonrpc":"2.0","result":{"__jsonclass__":["test_obj.TestSerial",[]],"foo":"bar"}}This behavior is turned on by default.
To deactivate it, just set theuse_jsonclassmember of a serverConfigtoFalse.
If you want to use a per-class serialization method, set its name in theserialize_methodmember of a serverConfig.
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
(onBOTHthe server and the client) using theconfig.classes.add()method.Feedback on this "feature" is very, VERY much appreciated.TestsTests are an almost-verbatim drop from the JSON-RPC specification 2.0
page. They can be run usingunittestornosetest:python -m unittest discover tests
python3 -m unittest discover tests
nosetests testsWhy 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 withjsonclass(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)