Python JSON-RPC Client Server Library With Additional Support for BaseHTTPServer, CherryPy And CGI
Python 100.00%
python-jsonrpc's Introduction
Python JSON-RPC Client Server Library With Additional Support for BaseHTTPServer, CherryPy And CGI
Installation
pip install python-jsonrpc
HTTP Client Example
#!/usr/bin/env python# coding: utf-8importpyjsonrpchttp_client=pyjsonrpc.HttpClient(
url="http://example.com/jsonrpc",
username="Username",
password="Password"
)
printhttp_client.call("add", 1, 2)
# Result: 3# It is also possible to use the *method* name as *attribute* name.printhttp_client.add(1, 2)
# Result: 3# Notifications send messages to the server, without response.http_client.notify("add", 3, 4)
#!/usr/bin/env python# coding: utf-8importpyjsonrpcdefadd(a, b):
"""Test function"""returna+b# Handles the JSON-RPC request and gets back the result to STDOUTpyjsonrpc.handle_cgi_request(methods=dict(add=add))
Library Usage Example
#!/usr/bin/env python# coding: utf-8importpyjsonrpcclassJsonRpc(pyjsonrpc.JsonRpc):
@pyjsonrpc.rpcmethoddefadd(self, a, b):
"""Test method"""returna+b# 1. Initialize JSON-RPC classrpc=JsonRpc()
# 2. Create JSON-RPC string with parameters (= request string)request_json=pyjsonrpc.create_request_json("add", 1, 2)
# request_json = '{"method": "add", "params": [1, 2], "id": "...", "jsonrpc": "2.0"}'# 3. Call the JSON-RPC function and get back the JSON-RPC result (= response string)response_json=rpc.call(request_json)
# response_json = '{"result": 3, "id": "...", "jsonrpc": "2.0"}'# 4. Convert JSON-RPC string to Python objectsresponse=pyjsonrpc.parse_response_json(response_json)
# 5. Print result or errorifresponse.error:
print"Error:", response.error.code, response.error.messageelse:
print"Result:", response.result
CherryPy Example
#!/usr/bin/env python# coding: utf-8importcherrypyfrompyjsonrpc.cpimportCherryPyJsonRpc, rpcmethodclassRoot(CherryPyJsonRpc):
@rpcmethoddefadd(self, a, b):
"""Test method"""returna+bindex=CherryPyJsonRpc.request_handlerprint"Starting HTTP server ..."print"URL: http://localhost:8080"cherrypy.quickstart(Root())
Licenses
GNU Library or Lesser General Public License (LGPL)