Foundations of Python Network Programming

(WallPaper) #1

Chapter 18 ■ rpC


338


Listing 18-4. Using XML-RPC Multicall


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


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


XML-RPC client performing a multicall


import xmlrpc.client


def main():
proxy = xmlrpc.client.ServerProxy('http://127.0.0.1:7001')
multicall = xmlrpc.client.MultiCall(proxy)
multicall.addtogether('a', 'b', 'c')
multicall.quadratic(2, -4, 0)
multicall.remote_repr([1, 2.0, 'three'])
for answer in multicall():
print(answer)


if name == 'main':
main()


When you run this script, you can watch the server’s command window to confirm that only a single HTTP
request is made in order to answer all three function calls that get made:


localhost - - [04/Oct/2010 00:16:19] "POST /RPC2 HTTP/1.0" 200 -


The ability to log messages like the preceding one can be turned off, by the way; such logging is controlled by one
of the options in SimpleXMLRPCServer. Note that the default URL used by both the server and the client is the path
/RPC2, unless you consult the documentation and configure the client and server differently.
Three final points are worth mentioning before I move on to examine another RPC mechanism:


•    There are two additional data types that sometimes prove hard to live without, so many
XML-RPC mechanisms support them: dates and the value that Python calls None (other
languages call this null or nil). Python’s client and server both support options that will
enable the transmission and reception of these nonstandard values.

•    Keyword arguments are, alas, not supported by XML-RPC because few languages are
sophisticated enough to include them. Some services get around this by allowing a dictionary
to be passed as a function’s final argument—or by disposing of positional arguments
altogether and using a single dictionary argument for every function that specifies all of its
parameters by name.

•    Finally, keep in mind that dictionaries can only be passed if all of their keys are strings,
whether normal or Unicode. See the “Self-Documenting Data” section later in this chapter for
more information on how to think about this restriction.

Although the entire point of an RPC protocol like XML-RPC is to let you forget about the details of network
transmission and focus on normal programming, you should see what your calls will look like on the wire at least
once! Here is the first call to quadratic() that the sample client program makes:


<?xml version='1.0'?>



quadratic
Free download pdf