Name | jsonrpclib-pelix JSON |
Version |
0.4.3.2
JSON |
| download |
home_page | http://github.com/tcalmant/jsonrpclib/ |
Summary | This project is an implementation of the JSON-RPC v2.0 specification (backwards-compatible) as a client library, for Python 2.7 and Python 3. This version is a fork of jsonrpclib by Josh Marshall, made to be also usable with Pelix/iPOPO remote services. |
upload_time | 2022-02-19 16:58:56 |
maintainer | |
docs_url | None |
author | Thomas Calmant |
requires_python | |
license | Apache License 2.0 |
keywords |
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
|
# JSONRPClib (patched for Pelix and Python 3)
[![Latest Version](https://img.shields.io/pypi/v/jsonrpclib-pelix.svg)](https://pypi.python.org/pypi/jsonrpclib-pelix/)
[![License](https://img.shields.io/pypi/l/jsonrpclib-pelix.svg)](https://pypi.python.org/pypi/jsonrpclib-pelix/)
[![Travis-CI status](https://travis-ci.org/tcalmant/jsonrpclib.svg?branch=master)](https://travis-ci.org/tcalmant/jsonrpclib)
[![Coveralls status](https://coveralls.io/repos/tcalmant/jsonrpclib/badge.svg?branch=master)](https://coveralls.io/r/tcalmant/jsonrpclib?branch=master)
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 the
[Apache Software License 2.0](<http://www.apache.org/licenses/LICENSE-2.0.html>).
## About this version
This is a patched version of the original `jsonrpclib` project by Josh Marshall,
available at
[joshmarshall/jsonrpclib](<https://github.com/joshmarshall/jsonrpclib>).
The suffix *-pelix* only indicates that this version works with Pelix
Remote Services, but it is **not** a 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 the `dispatch_method` argument while extending the
`SimpleJSONRPCDispatcher`, 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:
* From [drdaeman/jsonrpclib](<https://github.com/drdaeman/jsonrpclib>):
* Improved JSON-RPC 1.0 support
* Less strict error response handling
* From [tuomassalo/jsonrpclib](<https://github.com/tuomassalo/jsonrpclib>):
* In case of a non-predefined error, raise an AppError and give access
to *error.data*
* From [dejw/jsonrpclib](<https://github.com/dejw/jsonrpclib>):
* Custom headers can be sent with request and associated tests
* Since version 0.4, this package added back the support of Unix sockets.
* This package cannot be installed with the original `jsonrpclib`, as it uses
the same name.
## 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 the `MultiCall` class)
- Keyword arguments
- Notifications (both in a batch and 'normal')
- Class translation using the `__jsonclass__` key.
A `SimpleJSONRPCServer` class has been added. It is intended to emulate the
`SimpleXMLRPCServer` from the default Python distribution.
## Requirements
This library supports `ujson`, `cjson` and `simplejson`, and looks for the
parsers in that order (searching first for `ujson`, `cjson`, `simplejson`
and finally for the *built-in* `json`).
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 that `ujson` 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`
might be required):
```
# Global installation
pip install jsonrpclib-pelix
# Local installation
pip install --user jsonrpclib-pelix
```
Alternatively, you can download the source from the GitHub repository at
[tcalmant/jsonrpclib](http://github.com/tcalmant/jsonrpclib) and manually
install it with the following commands:
```
git clone git://github.com/tcalmant/jsonrpclib.git
cd jsonrpclib
python setup.py install
```
## A note on logging
`jsonrpclib-pelix` uses the `logging` module 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:
```python
import logging
logging.basiConfig()
```
More information can be found in the
[`logging` documentation page](https://docs.python.org/3/library/logging.html).
## `SimpleJSONRPCServer`
This is identical in usage (or should be) to the `SimpleXMLRPCServer` in 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 regular
`SimpleXMLRPCServer`, since the `SimpleJSONRPCServer` is provided by th
`jsonrpclib` library.
```python
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()
```
To start protect the server with SSL, use the following snippet:
```python
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
import ssl
# Setup the SSL socket
server = 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 server
server.serve_forever()
```
### Notification Thread Pool
By 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 the `set_notification_pool()` method:
```python
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
# Setup the thread pool: between 0 and 10 threads
pool = ThreadPool(max_threads=10, min_threads=0)
# Don't forget to start it
pool.start()
# Setup the server
server = SimpleJSONRPCServer(('localhost', 8080))
server.set_notification_pool(pool)
# Register methods
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_function(lambda x: 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 server
It is also possible to use a thread pool to handle clients requests, using the
`PooledJSONRPCServer` class.
By default, this class uses pool of 0 to 30 threads.
A custom pool can be given with the `thread_pool` parameter 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.
```python
from jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
# Setup the notification and request pools
nofif_pool = ThreadPool(max_threads=10, min_threads=0)
request_pool = ThreadPool(max_threads=50, min_threads=10)
# Don't forget to start them
nofif_pool.start()
request_pool.start()
# Setup the server
server = PooledJSONRPCServer(('localhost', 8080), thread_pool=request_pool)
server.set_notification_pool(nofif_pool)
# Register methods
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_function(lambda x: 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 socket
To start a server listening on a Unix socket, you will have to use the
following snippet:
```python
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
import os
import socket
# Set the path to the socket file
socket_name = "/tmp/my_socket.socket"
# Ensure that the file doesn't exist yet (or an error will be raised)
if os.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 server
srv.serve_forever()
except KeyboardInterrupt:
# Shutdown the server gracefully
srv.shutdown()
srv.server_close()
finally:
# You should clean up after the server stopped
os.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
the `AF_UNIX` address family.
## Client Usage
This is (obviously) taken from a console session.
```python
>>> import jsonrpclib
>>> 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()
>>> for result in results:
>>> ... 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 to
`jsonrpclib.ServerProxy`:
```python
>>> import jsonrpclib
>>> jsonrpclib.config.DEFAULT.version
2.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 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.
### Unix sockets
To 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.socket`
When 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.socket`
**Note:** Currently, only HTTP is supported over a Unix socket.
If you want HTTPS support to be implemented, please create an
[issue on GitHub](https://github.com/tcalmant/jsonrpclib/issues)
### Additional headers
If your remote service requires custom headers in request, you can pass them
using the `headers` keyword argument, when creating the `ServerProxy`:
```python
>>> import jsonrpclib
>>> server = jsonrpclib.ServerProxy("http://localhost:8080",
headers={'X-Test' : 'Test'})
```
You can also put additional request headers only for certain method
invocation:
```python
>>> import jsonrpclib
>>> server = jsonrpclib.Server("http://localhost:8080")
>>> with server._additional_headers({'X-Test' : 'Test'}) as test_server:
... test_server.ping(42)
...
>>> # X-Test header will be no longer sent in requests
```
Of course `_additional_headers` contexts can be nested as well.
## Class Translation
The 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 `_serialize` method (see usage below).
The server and client must **BOTH** have the `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).
* Sample file: `test_obj.py`
```python
# 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,})
```
- Sample usage:
```python
>>> import jsonrpclib
>>> import test_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 the `use_jsonclass` member of a server `Config` to
`False`.
If you want to use a per-class serialization method, set its name in the
`serialize_method` member of a server `Config`.
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 `config.classes.add()` method.
Feedback on this "feature" is very, VERY much appreciated.
## Tests
Tests are an almost-verbatim drop from the JSON-RPC specification 2.0
page. They can be run using *unittest* or *nosetest*:
```
python -m unittest discover tests
python3 -m unittest discover tests
nosetests tests
```
## 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)
Raw data
{
"_id": null,
"home_page": "http://github.com/tcalmant/jsonrpclib/",
"name": "jsonrpclib-pelix",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "",
"author": "Thomas Calmant",
"author_email": "thomas.calmant+github@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/f5/10/839b1d2cbd6157e4b09d4499c849b48127cd1d761e1d5bfeb1522c8be50d/jsonrpclib-pelix-0.4.3.2.tar.gz",
"platform": "",
"description": "# JSONRPClib (patched for Pelix and Python 3)\n\n[![Latest Version](https://img.shields.io/pypi/v/jsonrpclib-pelix.svg)](https://pypi.python.org/pypi/jsonrpclib-pelix/)\n[![License](https://img.shields.io/pypi/l/jsonrpclib-pelix.svg)](https://pypi.python.org/pypi/jsonrpclib-pelix/)\n[![Travis-CI status](https://travis-ci.org/tcalmant/jsonrpclib.svg?branch=master)](https://travis-ci.org/tcalmant/jsonrpclib)\n[![Coveralls status](https://coveralls.io/repos/tcalmant/jsonrpclib/badge.svg?branch=master)](https://coveralls.io/r/tcalmant/jsonrpclib?branch=master)\n\nThis library is an implementation of the JSON-RPC specification.\nIt supports both the original 1.0 specification, as well as the new\n(proposed) 2.0 specification, which includes batch submission, keyword\narguments, etc.\n\nThis library is licensed under the terms of the\n[Apache Software License 2.0](<http://www.apache.org/licenses/LICENSE-2.0.html>).\n\n\n## About this version\n\nThis is a patched version of the original `jsonrpclib` project by Josh Marshall,\navailable at\n[joshmarshall/jsonrpclib](<https://github.com/joshmarshall/jsonrpclib>).\n\nThe suffix *-pelix* only indicates that this version works with Pelix\nRemote Services, but it is **not** a Pelix specific implementation.\n\n* This version adds support for Python 3, staying compatible with Python 2.7.\n The support for Python 2.6 has been dropped, as it was becoming to hard to\n maintain.\n* It is now possible to use the `dispatch_method` argument while extending the\n `SimpleJSONRPCDispatcher`, to use a custom dispatcher.\n This allows to use this package by Pelix Remote Services.\n* It can use thread pools to control the number of threads spawned to handle\n notification requests and clients connections.\n* The modifications added in other forks of this project have been added:\n * From [drdaeman/jsonrpclib](<https://github.com/drdaeman/jsonrpclib>):\n * Improved JSON-RPC 1.0 support\n * Less strict error response handling\n * From [tuomassalo/jsonrpclib](<https://github.com/tuomassalo/jsonrpclib>):\n * In case of a non-predefined error, raise an AppError and give access\n to *error.data*\n * From [dejw/jsonrpclib](<https://github.com/dejw/jsonrpclib>):\n * Custom headers can be sent with request and associated tests\n* Since version 0.4, this package added back the support of Unix sockets.\n* This package cannot be installed with the original `jsonrpclib`, as it uses\n the same name.\n\n## Summary\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 the `MultiCall` class)\n- Keyword arguments\n- Notifications (both in a batch and 'normal')\n- Class translation using the `__jsonclass__` key.\n\nA `SimpleJSONRPCServer` class has been added. It is intended to emulate the\n`SimpleXMLRPCServer` from the default Python distribution.\n\n## Requirements\n\nThis library supports `ujson`, `cjson` and `simplejson`, and looks for the\nparsers in that order (searching first for `ujson`, `cjson`, `simplejson`\nand finally for the *built-in* `json`).\nOne of these must be installed to use this library, although if you have a\nstandard distribution of 2.7+, you should already have one.\nKeep in mind that `ujson` is supposed to be the quickest, I believe, so if you\nare going for full-on optimization you may want to pick it up.\n\n## Installation\n\nYou can install this from PyPI with one of the following commands (`sudo`\nmight be required):\n\n```\n# Global installation\npip install jsonrpclib-pelix\n\n# Local installation\npip install --user jsonrpclib-pelix\n```\n\nAlternatively, you can download the source from the GitHub repository at\n[tcalmant/jsonrpclib](http://github.com/tcalmant/jsonrpclib) and manually\ninstall it with the following commands:\n\n```\ngit clone git://github.com/tcalmant/jsonrpclib.git\ncd jsonrpclib\npython setup.py install\n```\n\n## A note on logging\n\n`jsonrpclib-pelix` uses the `logging` module from the standard Python\nlibrary to trace warnings and errors, but doesn't set it up.\nAs a result, you have to configure the Python logging to print out traces.\n\nThe easiest way to do it is to add those lines at the beginning of your code:\n```python\nimport logging\nlogging.basiConfig()\n```\n\nMore information can be found in the\n[`logging` documentation page](https://docs.python.org/3/library/logging.html).\n\n## `SimpleJSONRPCServer`\n\nThis is identical in usage (or should be) to the `SimpleXMLRPCServer` in the\nPython standard library.\nSome of the differences in features are that it obviously supports notification,\nbatch calls, class translation (if left on), etc.\n\n**Note:** The import line is slightly different from the regular\n`SimpleXMLRPCServer`, since the `SimpleJSONRPCServer` is provided by th\n`jsonrpclib` library.\n\n```python\nfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\n\nserver = SimpleJSONRPCServer(('localhost', 8080))\nserver.register_function(pow)\nserver.register_function(lambda x,y: x+y, 'add')\nserver.register_function(lambda x: x, 'ping')\nserver.serve_forever()\n```\n\nTo start protect the server with SSL, use the following snippet:\n\n```python\nfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\nimport ssl\n\n# Setup the SSL socket\nserver = SimpleJSONRPCServer(('localhost', 8080), bind_and_activate=False)\nserver.socket = ssl.wrap_socket(server.socket, certfile='server.pem',\n server_side=True)\nserver.server_bind()\nserver.server_activate()\n\n# ... register functions\n# Start the server\nserver.serve_forever()\n```\n\n### Notification Thread Pool\n\nBy default, notification calls are handled in the request handling thread.\nIt is possible to use a thread pool to handle them, by giving it to the server\nusing the `set_notification_pool()` method:\n\n```python\nfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\nfrom jsonrpclib.threadpool import ThreadPool\n\n# Setup the thread pool: between 0 and 10 threads\npool = ThreadPool(max_threads=10, min_threads=0)\n\n# Don't forget to start it\npool.start()\n\n# Setup the server\nserver = SimpleJSONRPCServer(('localhost', 8080))\nserver.set_notification_pool(pool)\n\n# Register methods\nserver.register_function(pow)\nserver.register_function(lambda x,y: x+y, 'add')\nserver.register_function(lambda x: x, 'ping')\n\ntry:\n server.serve_forever()\nfinally:\n # Stop the thread pool (let threads finish their current task)\n pool.stop()\n server.set_notification_pool(None)\n```\n\n### Threaded server\n\nIt is also possible to use a thread pool to handle clients requests, using the\n`PooledJSONRPCServer` class.\nBy default, this class uses pool of 0 to 30 threads.\nA custom pool can be given with the `thread_pool` parameter of the class\nconstructor.\n\nThe notification pool and the request pool are different: by default, a server\nwith a request pool doesn't have a notification pool.\n\n```python\nfrom jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer\nfrom jsonrpclib.threadpool import ThreadPool\n\n# Setup the notification and request pools\nnofif_pool = ThreadPool(max_threads=10, min_threads=0)\nrequest_pool = ThreadPool(max_threads=50, min_threads=10)\n\n# Don't forget to start them\nnofif_pool.start()\nrequest_pool.start()\n\n# Setup the server\nserver = PooledJSONRPCServer(('localhost', 8080), thread_pool=request_pool)\nserver.set_notification_pool(nofif_pool)\n\n# Register methods\nserver.register_function(pow)\nserver.register_function(lambda x,y: x+y, 'add')\nserver.register_function(lambda x: x, 'ping')\n\ntry:\n server.serve_forever()\nfinally:\n # Stop the thread pools (let threads finish their current task)\n request_pool.stop()\n nofif_pool.stop()\n server.set_notification_pool(None)\n```\n\n### Unix socket\n\nTo start a server listening on a Unix socket, you will have to use the\nfollowing snippet:\n\n```python\nfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\nimport os\nimport socket\n\n# Set the path to the socket file\nsocket_name = \"/tmp/my_socket.socket\"\n\n# Ensure that the file doesn't exist yet (or an error will be raised)\nif os.path.exists(socket_name):\n os.remove(socket_name)\n\ntry:\n # Start the server, indicating the socket family\n # The server will force some flags when in Unix socket mode\n # (no log request, no reuse address, ...)\n srv = SimpleJSONRPCServer(socket_name, address_family=socket.AF_UNIX)\n\n # ... register methods to the server\n # Run the server\n srv.serve_forever()\nexcept KeyboardInterrupt:\n # Shutdown the server gracefully\n srv.shutdown()\n srv.server_close()\nfinally:\n # You should clean up after the server stopped\n os.remove(socket_name)\n```\n\nThis feature is tested on Linux during Travis-CI builds. It also has\nbeen tested on Windows Subsystem for Linux (WSL) on Windows 10 1809.\n\nThis feature is not available on \"pure\" Windows, as it doesn't provide\nthe `AF_UNIX` address family.\n\n## Client Usage\n\nThis is (obviously) taken from a console session.\n\n```python\n>>> import jsonrpclib\n>>> server = jsonrpclib.ServerProxy('http://localhost:8080')\n>>> server.add(5,6)\n11\n>>> server.add(x=5, y=10)\n15\n>>> server._notify.add(5,6)\n# No result returned...\n>>> batch = jsonrpclib.MultiCall(server)\n>>> batch.add(5, 6)\n>>> batch.ping({'key':'value'})\n>>> batch._notify.add(4, 30)\n>>> results = batch()\n>>> for result in results:\n>>> ... print(result)\n11\n{'key': 'value'}\n# Note that there are only two responses -- this is according to spec.\n\n# Clean up\n>>> server('close')()\n\n# Using client history\n>>> history = jsonrpclib.history.History()\n>>> server = jsonrpclib.ServerProxy('http://localhost:8080', history=history)\n>>> server.add(5,6)\n11\n>>> print(history.request)\n{\"id\": \"f682b956-c8e1-4506-9db4-29fe8bc9fcaa\", \"jsonrpc\": \"2.0\",\n \"method\": \"add\", \"params\": [5, 6]}\n>>> print(history.response)\n{\"id\": \"f682b956-c8e1-4506-9db4-29fe8bc9fcaa\", \"jsonrpc\": \"2.0\",\n \"result\": 11}\n\n# Clean up\n>>> server('close')()\n```\n\nIf you need 1.0 functionality, there are a bunch of places you can pass\nthat in, although the best is just to give a specific configuration to\n`jsonrpclib.ServerProxy`:\n\n```python\n>>> import jsonrpclib\n>>> jsonrpclib.config.DEFAULT.version\n2.0\n>>> config = jsonrpclib.config.Config(version=1.0)\n>>> history = jsonrpclib.history.History()\n>>> server = jsonrpclib.ServerProxy('http://localhost:8080', config=config,\n history=history)\n>>> server.add(7, 10)\n17\n>>> print(history.request)\n{\"id\": \"827b2923-5b37-49a5-8b36-e73920a16d32\",\n \"method\": \"add\", \"params\": [7, 10]}\n>>> print(history.response)\n{\"id\": \"827b2923-5b37-49a5-8b36-e73920a16d32\", \"error\": null, \"result\": 17}\n>>> server('close')()\n```\n\nThe equivalent `loads` and `dumps` functions also exist, although with\nminor modifications.\nThe `dumps` arguments are almost identical, but it adds three arguments:\n`rpcid` for the `id` key, `version` to specify the JSON-RPC compatibility,\nand `notify` if it's a request that you want to be a notification.\n\nAdditionally, the `loads` method does not return the params and method like\n`xmlrpclib`, but instead\na.) parses for errors, raising ProtocolErrors, and\nb.) returns the entire structure of the request / response for manual parsing.\n\n### Unix sockets\n\nTo connect a JSON-RPC server over a Unix socket, you have to use a specific\nprotocol: `unix+http`.\n\nWhen connecting to a Unix socket in the current working directory, you can use\nthe following syntax: `unix+http://my.socket`\n\nWhen you need to give an absolute path you must use the path part of the URL,\nthe host part will be ignored. For example, you can use this URL to indicate a\nUnix socket in `/var/lib/daemon.socket`: `unix+http://./var/lib/daemon.socket`\n\n**Note:** Currently, only HTTP is supported over a Unix socket.\nIf you want HTTPS support to be implemented, please create an\n[issue on GitHub](https://github.com/tcalmant/jsonrpclib/issues)\n\n### Additional headers\n\nIf your remote service requires custom headers in request, you can pass them\nusing the `headers` keyword argument, when creating the `ServerProxy`:\n\n```python\n>>> import jsonrpclib\n>>> server = jsonrpclib.ServerProxy(\"http://localhost:8080\",\n headers={'X-Test' : 'Test'})\n```\n\nYou can also put additional request headers only for certain method\ninvocation:\n\n```python\n>>> import jsonrpclib\n>>> server = jsonrpclib.Server(\"http://localhost:8080\")\n>>> with server._additional_headers({'X-Test' : 'Test'}) as test_server:\n... test_server.ping(42)\n...\n>>> # X-Test header will be no longer sent in requests\n```\n\nOf course `_additional_headers` contexts can be nested as well.\n\n## Class Translation\n\nThe library supports an *\"automatic\"* class translation process, although it\nis turned off by default.\nThis can be devastatingly slow if improperly used, so the following is just a\nshort 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 the `use_jsonclass` configuration\nitem on and they must both have access to the same libraries used by the\nobjects for this 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\n`jsonrpclib.jsonclass.dump` / `jsonrpclib.jsonclass.load` (since the\ndefault behavior recursively goes through attributes and lists/dicts/tuples).\n\n* Sample file: `test_obj.py`\n\n```python\n# This object is /very/ simple, and the system will look through the\n# attributes and serialize what it can.\nclass TestObj(object):\n foo = 'bar'\n\n# This object requires __init__ params, so it uses the _serialize method\n# and returns a tuple of init params and attribute values (the init params\n# can be a dict or a list, but the attribute values must be a dict.)\nclass TestSerial(object):\n foo = 'bar'\n def __init__(self, *args):\n self.args = args\n def _serialize(self):\n return (self.args, {'foo':self.foo,})\n```\n\n- Sample usage:\n\n```python\n>>> import jsonrpclib\n>>> import test_obj\n\n# History is used only to print the serialized form of beans\n>>> history = jsonrpclib.history.History()\n>>> testobj1 = test_obj.TestObj()\n>>> testobj2 = test_obj.TestSerial()\n>>> server = jsonrpclib.Server('http://localhost:8080', history=history)\n\n# The 'ping' just returns whatever is sent\n>>> ping1 = server.ping(testobj1)\n>>> ping2 = server.ping(testobj2)\n\n>>> print(history.request)\n{\"id\": \"7805f1f9-9abd-49c6-81dc-dbd47229fe13\", \"jsonrpc\": \"2.0\",\n \"method\": \"ping\", \"params\": [{\"__jsonclass__\":\n [\"test_obj.TestSerial\", []], \"foo\": \"bar\"}\n ]}\n>>> print(history.response)\n{\"id\": \"7805f1f9-9abd-49c6-81dc-dbd47229fe13\", \"jsonrpc\": \"2.0\",\n \"result\": {\"__jsonclass__\": [\"test_obj.TestSerial\", []], \"foo\": \"bar\"}}\n```\n\nThis behavior is turned on by default.\nTo deactivate it, just set the `use_jsonclass` member of a server `Config` to\n`False`.\nIf you want to use a per-class serialization method, set its name in the\n`serialize_method` member of a server `Config`.\nFinally, if you are using classes that you have defined in the implementation\n(as in, not a separate library), you'll need to add those\n(on **BOTH** the server and the client) using the `config.classes.add()` method.\n\nFeedback on this \"feature\" is very, VERY much appreciated.\n\n## Tests\n\nTests are an almost-verbatim drop from the JSON-RPC specification 2.0\npage. They can be run using *unittest* or *nosetest*:\n\n```\npython -m unittest discover tests\npython3 -m unittest discover tests\nnosetests tests\n```\n\n## Why 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\n 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 over\nJSON:\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\n\n",
"bugtrack_url": null,
"license": "Apache License 2.0",
"summary": "This project is an implementation of the JSON-RPC v2.0 specification (backwards-compatible) as a client library, for Python 2.7 and Python 3. This version is a fork of jsonrpclib by Josh Marshall, made to be also usable with Pelix/iPOPO remote services.",
"version": "0.4.3.2",
"project_urls": {
"Homepage": "http://github.com/tcalmant/jsonrpclib/"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "8c1a378f7aed3fb2a4b27fbde3afb164f521e0deb496b4965a0ea0b4a5bf1c0d",
"md5": "669b5684f03b7cc8a30200bf23481542",
"sha256": "a9c0178317562a179e83deb27f753840fad4afe3b2bd1ee64495592ce3df1b28"
},
"downloads": -1,
"filename": "jsonrpclib_pelix-0.4.3.2-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "669b5684f03b7cc8a30200bf23481542",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 42489,
"upload_time": "2022-02-19T16:58:54",
"upload_time_iso_8601": "2022-02-19T16:58:54.020876Z",
"url": "https://files.pythonhosted.org/packages/8c/1a/378f7aed3fb2a4b27fbde3afb164f521e0deb496b4965a0ea0b4a5bf1c0d/jsonrpclib_pelix-0.4.3.2-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "f510839b1d2cbd6157e4b09d4499c849b48127cd1d761e1d5bfeb1522c8be50d",
"md5": "3fa58323bbb094dfc59dc2327d99359c",
"sha256": "e9e0b33efa8fa20d817dd78dfd9e4cdb3967c8a5d3cb5a783be1ee81c4a89c7c"
},
"downloads": -1,
"filename": "jsonrpclib-pelix-0.4.3.2.tar.gz",
"has_sig": false,
"md5_digest": "3fa58323bbb094dfc59dc2327d99359c",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 43147,
"upload_time": "2022-02-19T16:58:56",
"upload_time_iso_8601": "2022-02-19T16:58:56.144931Z",
"url": "https://files.pythonhosted.org/packages/f5/10/839b1d2cbd6157e4b09d4499c849b48127cd1d761e1d5bfeb1522c8be50d/jsonrpclib-pelix-0.4.3.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-02-19 16:58:56",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "tcalmant",
"github_project": "jsonrpclib",
"travis_ci": false,
"coveralls": true,
"github_actions": true,
"lcname": "jsonrpclib-pelix"
}