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