Welcome to JSONRPC’s documentation!¶
Contents:
Getting Started¶
This code will create a server that logs all requests, and provides two methods to clients: add and subtract:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | #
# Copyright (c) 2011 Edward Langley
from twisted.internet import reactor, ssl
from twisted.web import server
import traceback
from jsonrpc.server import ServerEvents, JSON_RPC
class ExampleServer(ServerEvents):
# inherited hooks
def log(self, responses, txrequest, error):
print(txrequest.code, end=' ')
if isinstance(responses, list):
for response in responses:
msg = self._get_msg(response)
print(txrequest, msg)
else:
msg = self._get_msg(responses)
print(txrequest, msg)
def findmethod(self, method, args=None, kwargs=None):
if method in self.methods:
return getattr(self, method)
else:
return None
# helper methods
methods = set(['add', 'subtract'])
def _get_msg(self, response):
print('response', repr(response))
return ' '.join(str(x) for x in [response.id, response.result or response.error])
def subtract(self, a, b):
return a-b
def add(self, a, b):
return a+b
root = JSON_RPC().customize(ExampleServer)
site = server.Site(root)
# 8007 is the port you want to run under. Choose something >1024
PORT = 8007
print('Listening on port %d...' % PORT)
reactor.listenTCP(PORT, site)
reactor.run()
|
To use this server (which is included as jsonrpc.example_server), start it and the client in this way:
% python -m jsonrpc.example_server &
% python -i -m jsonrpc.__main__ http://localhost:8007
>>> server.add(1,2)
3
>>> server.subtract(3,2)
1
>>> server.batch_call(dict(
... add = ((3, 2), {} ),
... subtract = ((), {'a': 3, 'b': 2})
... ))
[(5, None), (1, None)]
JSON-RPC Server¶
JSON-RPC Proxy¶
-
class
jsonrpc.proxy.
JSONRPCProxy
(host, path='jsonrpc', serviceName=None, *args, **kwargs)[source]¶ A class implementing a JSON-RPC Proxy.
Parameters: There are two ways of instantiating this class: - JSONRPCProxy.from_url(url) – give the absolute url to the JSON-RPC server - JSONRPC(host, path) – break up the url into smaller parts
-
batch_call
(methods)[source]¶ call several methods at once, return a list of (result, error) pairs
Parameters: names – a dictionary { method: (args, kwargs) } Returns: a list of pairs (result, error) where only one is not None
-
-
class
jsonrpc.proxy.
ProxyEvents
(proxy)[source]¶ An event handler for JSONRPCProxy
Allow a subclass to do its own initialization, gets any arguments leftover from __init__
-
IDGen
= '9b2c21e1de2e62fb30d63f617932fba27bd03148'¶ an instance of a class which defines a __get__ method, used to generate a request id
-
jsonrpc.jsonutil¶
-
jsonrpc.jsonutil.
encode
(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', **kw)¶ Serialize obj to json, if it is not of a type which the encoder can handle, make it the proper type. Args and kw are as in json.dumps
-
jsonrpc.jsonutil.
decode
(str, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw)¶ Return an object from a json string. This is just
json.loads()
renamed