Foundations of Python Network Programming

(WallPaper) #1

Chapter 18 ■ rpC


334


import operator, math
from xmlrpc.server import SimpleXMLRPCServer
from functools import reduce


def main():
server = SimpleXMLRPCServer(('127.0.0.1', 7001))
server.register_introspection_functions()
server.register_multicall_functions()
server.register_function(addtogether)
server.register_function(quadratic)
server.register_function(remote_repr)
print("Server ready")
server.serve_forever()


def addtogether(*things):
"""Add together everything in the list things."""
return reduce(operator.add, things)


def quadratic(a, b, c):
"""Determine x values satisfying: a xx + b x + c == 0"""
b24ac = math.sqrt(b
b - 4.0ac)
return list(set([ (-b-b24ac) / 2.0a,
(-b+b24ac) / 2.0
a ]))


def remote_repr(arg):
"""Return the repr() rendering of the supplied arg."""
return arg


if name == 'main':
main()


An XML-RPC service lives at a single URL of a web site, so you do not actually have to dedicate an entire port to
an RPC service like this. Instead, you can integrate it with a normal web application that offers all sorts of other pages,
or even separate RPC services, at other URLs. But if you do have an entire port to spare, then the Python XML-RPC
server offers an easy way to bring up a web server that does nothing but talk XML-RPC.
You can see that the three sample functions that the server offers over XML-RPC (the ones that are added to the
RPC service through the register_function() calls) are quite typical Python functions. And that again is the whole
point of XML-RPC—it lets you make routines available for invocation over the network without having to write them
any differently than if they were normal functions offered inside your program.
The SimpleXMLRPCServer offered by the Python Standard Library is, as its name implies, quite simple; it cannot
offer other web pages, it does not understand any kind of HTTP authentication, and you cannot ask it to offer
TLS security without subclassing it yourself and adding more code. Nevertheless, it will serve the purposes here
admirably, showing you some of the basic features and limits of RPC while also letting you get up and running in only
a few lines of code.
Note that two additional configuration calls are made in addition to the three calls that register the functions.
Each of them turns on an additional service that is optional but often provided by XML-RPC servers: an introspection
routine that a client can use to ask which RPC calls are supported by a given server, and the ability to support a
multicall function that lets several individual function calls be bundled together into a single network roundtrip.

Free download pdf