Foundations of Python Network Programming

(WallPaper) #1

Chapter 18 ■ rpC


340


JSON-RPC is not supported in the Python Standard Library, so you will have to choose one of the several
third-party distributions available. You can find these distributions on the Python Package Index. One of the first to
officially support Python 3 is jsonrpclib-pelix. If you install it in a virtual environment (see Chapter 1), then you
can try out the server and client presented in Listings 18-5 and 18-6, respectively.


Listing 18-5. A JSON-RPC Server


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


github.com/brandon-rhodes/fopnp/blob/m/py3/chapter18/jsonrpc_server.py


JSON-RPC server needing "pip install jsonrpclib-pelix"


from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer


def lengths(*args):
"""Measure the length of each input argument.


Given N arguments, this function returns a list of N smaller
lists of the form [len(arg), arg] that each state the length of
an input argument and also echo back the argument itself.


"""
results = []
for arg in args:
try:
arglen = len(arg)
except TypeError:
arglen = None
results.append((arglen, arg))
return results


def main():
server = SimpleJSONRPCServer(('localhost', 7002))
server.register_function(lengths)
print("Starting server")
server.serve_forever()


if name == 'main':
main()


The server code is quite simple, as an RPC mechanism should be. As with XML-RPC, you merely need to name
the functions you want offered over the network, and they become available for queries. (You can also pass an object,
and its methods will be registered with the server all at once.)


Listing 18-6. JSON-RPC Client


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


github.com/brandon-rhodes/fopnp/blob/m/py3/chapter18/jsonrpc_client.py


JSON-RPC client needing "pip install jsonrpclib-pelix"

Free download pdf