jsonrpclib


Namejsonrpclib JSON
Version 0.2.1 PyPI version JSON
download
home_pagehttps://github.com/joshmarshall/jsonrpclib
SummaryImplementation of the JSON-RPC v2.0 specification (backwards-compatible) as a client library.
upload_time2021-03-31 08:33:57
maintainer
docs_urlNone
authorJosh Marshall
requires_python>=3.5
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![Build Status](https://circleci.com/gh/joshmarshall/jsonrpclib.svg?style=svg)](https://circleci.com/gh/joshmarshall/jsonrpclib)


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.

Installation
------------
You can install this from PyPI with one of the following commands (sudo
may be required):

	easy_install jsonrpclib
	pip install jsonrpclib

Alternatively, you can download the source from the github repository
at http://github.com/joshmarshall/jsonrpclib and manually install it
with the following commands:

	git clone git://github.com/joshmarshall/jsonrpclib.git
	cd jsonrpclib
	python setup.py install

Client Usage
------------

This is (obviously) taken from a console session.

	>>> 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.

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: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}
	>>> 

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.

	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()

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]

	# 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

	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'}

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:

    pip install -r dev-requirements.txt
    nosetests tests.py

TODO
----
* Use HTTP error codes on SimpleJSONRPCServer
* Test, test, test and optimize



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/joshmarshall/jsonrpclib",
    "name": "jsonrpclib",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.5",
    "maintainer_email": "",
    "keywords": "",
    "author": "Josh Marshall",
    "author_email": "catchjosh@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/55/03/1b8b9f4514a7904c2511448cb04523f3123b31c6cd6ece968dacc8ea100d/jsonrpclib-0.2.1.tar.gz",
    "platform": "",
    "description": "[![Build Status](https://circleci.com/gh/joshmarshall/jsonrpclib.svg?style=svg)](https://circleci.com/gh/joshmarshall/jsonrpclib)\n\n\nJSONRPClib\n==========\nThis library is an implementation of the JSON-RPC specification.\nIt supports both the original 1.0 specification, as well as the \nnew (proposed) 2.0 spec, which includes batch submission, keyword\narguments, etc.\n\nIt is licensed under the Apache License, Version 2.0\n(http://www.apache.org/licenses/LICENSE-2.0.html).\n\nCommunication\n-------------\nFeel free to send any questions, comments, or patches to our Google Group \nmailing list (you'll need to join to send a message): \nhttp://groups.google.com/group/jsonrpclib\n\nSummary\n-------\nThis library implements the JSON-RPC 2.0 proposed specification in pure Python. \nIt is designed to be as compatible with the syntax of xmlrpclib as possible \n(it extends where possible), so that projects using xmlrpclib could easily be \nmodified to use JSON and experiment with the differences.\n\nIt is backwards-compatible with the 1.0 specification, and supports all of the \nnew proposed features of 2.0, including:\n\n* Batch submission (via MultiCall)\n* Keyword arguments\n* Notifications (both in a batch and 'normal')\n* Class translation using the 'jsonclass' key.\n\nI've added a \"SimpleJSONRPCServer\", which is intended to emulate the \n\"SimpleXMLRPCServer\" from the default Python distribution.\n\nRequirements\n------------\nIt supports cjson and simplejson, and looks for the parsers in that order \n(searching first for cjson, then for the \"built-in\" simplejson as json in 2.6+, \nand then the simplejson external library). One of these must be installed to \nuse this library, although if you have a standard distribution of 2.6+, you \nshould already have one. Keep in mind that cjson is supposed to be the \nquickest, I believe, so if you are going for full-on optimization you may \nwant to pick it up.\n\nInstallation\n------------\nYou can install this from PyPI with one of the following commands (sudo\nmay be required):\n\n\teasy_install jsonrpclib\n\tpip install jsonrpclib\n\nAlternatively, you can download the source from the github repository\nat http://github.com/joshmarshall/jsonrpclib and manually install it\nwith the following commands:\n\n\tgit clone git://github.com/joshmarshall/jsonrpclib.git\n\tcd jsonrpclib\n\tpython setup.py install\n\nClient Usage\n------------\n\nThis is (obviously) taken from a console session.\n\n\t>>> import jsonrpclib\n\t>>> server = jsonrpclib.Server('http://localhost:8080')\n\t>>> server.add(5,6)\n\t11\n\t>>> print jsonrpclib.history.request\n\t{\"jsonrpc\": \"2.0\", \"params\": [5, 6], \"id\": \"gb3c9g37\", \"method\": \"add\"}\n\t>>> print jsonrpclib.history.response\n\t{'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}\n\t>>> server.add(x=5, y=10)\n\t15\n\t>>> server._notify.add(5,6)\n\t# No result returned...\n\t>>> batch = jsonrpclib.MultiCall(server)\n\t>>> batch.add(5, 6)\n\t>>> batch.ping({'key':'value'})\n\t>>> batch._notify.add(4, 30)\n\t>>> results = batch()\n\t>>> for result in results:\n\t>>> ... print result\n\t11\n\t{'key': 'value'}\n\t# Note that there are only two responses -- this is according to spec.\n\nIf you need 1.0 functionality, there are a bunch of places you can pass that \nin, although the best is just to change the value on \njsonrpclib.config.version:\n\n\t>>> import jsonrpclib\n\t>>> jsonrpclib.config.version\n\t2.0\n\t>>> jsonrpclib.config.version = 1.0\n\t>>> server = jsonrpclib.Server('http://localhost:8080')\n\t>>> server.add(7, 10)\n\t17\n\t>>> print jsonrpclib..history.request\n\t{\"params\": [7, 10], \"id\": \"thes7tl2\", \"method\": \"add\"}\n\t>>> print jsonrpclib.history.response\n\t{'id': 'thes7tl2', 'result': 17, 'error': None}\n\t>>> \n\nThe equivalent loads and dumps functions also exist, although with minor \nmodifications. The dumps arguments are almost identical, but it adds three \narguments: rpcid for the 'id' key, version to specify the JSON-RPC \ncompatibility, and notify if it's a request that you want to be a \nnotification. \n\nAdditionally, the loads method does not return the params and method like \nxmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and \nb.) returns the entire structure of the request / response for manual parsing.\n\nSimpleJSONRPCServer\n-------------------\nThis 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.\n\n\tfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\n\n\tserver = SimpleJSONRPCServer(('localhost', 8080))\n\tserver.register_function(pow)\n\tserver.register_function(lambda x,y: x+y, 'add')\n\tserver.register_function(lambda x: x, 'ping')\n\tserver.serve_forever()\n\nClass Translation\n-----------------\nI've recently added \"automatic\" class translation support, although it is \nturned off by default. This can be devastatingly slow if improperly used, so \nthe following is just a short list of things to keep in mind when using it.\n\n* Keep It (the object) Simple Stupid. (for exceptions, keep reading.)\n* Do not require init params (for exceptions, keep reading)\n* Getter properties without setters could be dangerous (read: not tested)\n\nIf any of the above are issues, use the _serialize method. (see usage below)\nThe server and client must BOTH have use_jsonclass configuration item on and \nthey must both have access to the same libraries used by the objects for \nthis to work.\n\nIf you have excessively nested arguments, it would be better to turn off the \ntranslation and manually invoke it on specific objects using \njsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default \nbehavior recursively goes through attributes and lists / dicts / tuples).\n\n[test_obj.py]\n\n\t# This object is /very/ simple, and the system will look through the \n\t# attributes and serialize what it can.\n\tclass TestObj(object):\n\t    foo = 'bar'\n\n\t# This object requires __init__ params, so it uses the _serialize method\n\t# and returns a tuple of init params and attribute values (the init params\n\t# can be a dict or a list, but the attribute values must be a dict.)\n\tclass TestSerial(object):\n\t    foo = 'bar'\n\t    def __init__(self, *args):\n\t        self.args = args\n\t    def _serialize(self):\n\t        return (self.args, {'foo':self.foo,})\n\n[usage]\n\n\timport jsonrpclib\n\timport test_obj\n\n\tjsonrpclib.config.use_jsonclass = True\n\n\ttestobj1 = test_obj.TestObj()\n\ttestobj2 = test_obj.TestSerial()\n\tserver = jsonrpclib.Server('http://localhost:8080')\n\t# The 'ping' just returns whatever is sent\n\tping1 = server.ping(testobj1)\n\tping2 = server.ping(testobj2)\n\tprint jsonrpclib.history.request\n\t# {\"jsonrpc\": \"2.0\", \"params\": [{\"__jsonclass__\": [\"test_obj.TestSerial\", [\"foo\"]]}], \"id\": \"a0l976iv\", \"method\": \"ping\"}\n\tprint jsonrpclib.history.result\n\t# {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}\n\nTo turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True. \nIf you want to use a different method for serialization, just set \njsonrpclib.config.serialize_method to the method name. Finally, if you are \nusing classes that you have defined in the implementation (as in, not a \nseparate library), you'll need to add those (on BOTH the server and the \nclient) using the jsonrpclib.config.classes.add() method. \n(Examples forthcoming.)\n\nFeedback on this \"feature\" is very, VERY much appreciated.\n\nWhy JSON-RPC?\n-------------\nIn my opinion, there are several reasons to choose JSON over XML for RPC:\n\n* Much simpler to read (I suppose this is opinion, but I know I'm right. :)\n* Size / Bandwidth - Main reason, a JSON object representation is just much smaller.\n* Parsing - JSON should be much quicker to parse than XML.\n* Easy class passing with jsonclass (when enabled)\n\nIn the interest of being fair, there are also a few reasons to choose XML \nover JSON:\n\n* Your server doesn't do JSON (rather obvious)\n* Wider XML-RPC support across APIs (can we change this? :))\n* Libraries are more established, i.e. more stable (Let's change this too.)\n\nTESTS\n-----\nI've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.\nYou can run it with:\n\n    pip install -r dev-requirements.txt\n    nosetests tests.py\n\nTODO\n----\n* Use HTTP error codes on SimpleJSONRPCServer\n* Test, test, test and optimize\n\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Implementation of the JSON-RPC v2.0 specification (backwards-compatible) as a client library.",
    "version": "0.2.1",
    "project_urls": {
        "Homepage": "https://github.com/joshmarshall/jsonrpclib"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2a7fe303c32b29ff1ad93b0c106ba148a49006a624e7c8ce65b73f2ff14a4493",
                "md5": "7693ef30b111b120eeefc130a7c917be",
                "sha256": "5a571d3e46fe4f2fe7e607e1732b8a9ad6b7255f53bfbf465822fe1100baf538"
            },
            "downloads": -1,
            "filename": "jsonrpclib-0.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7693ef30b111b120eeefc130a7c917be",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5",
            "size": 15955,
            "upload_time": "2021-03-31T08:33:55",
            "upload_time_iso_8601": "2021-03-31T08:33:55.617290Z",
            "url": "https://files.pythonhosted.org/packages/2a/7f/e303c32b29ff1ad93b0c106ba148a49006a624e7c8ce65b73f2ff14a4493/jsonrpclib-0.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "55031b8b9f4514a7904c2511448cb04523f3123b31c6cd6ece968dacc8ea100d",
                "md5": "827d1441ac8304647e7c758cc6253b7d",
                "sha256": "8138078fd0f2a5b1df7925e4fa0b82a7c17a4be75bf5634af20463172f44f5c0"
            },
            "downloads": -1,
            "filename": "jsonrpclib-0.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "827d1441ac8304647e7c758cc6253b7d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5",
            "size": 18096,
            "upload_time": "2021-03-31T08:33:57",
            "upload_time_iso_8601": "2021-03-31T08:33:57.008128Z",
            "url": "https://files.pythonhosted.org/packages/55/03/1b8b9f4514a7904c2511448cb04523f3123b31c6cd6ece968dacc8ea100d/jsonrpclib-0.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2021-03-31 08:33:57",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "joshmarshall",
    "github_project": "jsonrpclib",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "circle": true,
    "tox": true,
    "lcname": "jsonrpclib"
}
        
Elapsed time: 0.37747s