Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Serving XML-RPC Requests

Credit: Brian Quinlan

Problem

You need to implement an XML-RPC server.

Solution

The xmlrpclib package also makes writing XML-RPC servers pretty easy. Here’s how you can write an XML-RPC server:

# server coder sxr_server.py
# needs Python 2.2 or the XML-RPC package from PythonWare

import SimpleXMLRPCServer

class StringFunctions:
    def _ _init_ _(self):
        # Make all of the Python string functions available through
        # python_string.func_name
        import string
        self.python_string = string

    def _privateFunction(self):
        # This function cannot be called directly through XML-RPC because
        # it starts with an underscore character '_', i.e., it's "private"
        pass

    def chop_in_half(self, astr):
        return astr[:len(astr)/2]

    def repeat(self, astr, times):
        return astr * times

if _ _name_ _=='_ _main_ _':
    server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000))
    server.register_instance(StringFunctions(  ))
    server.register_function(lambda astr: '_' + astr, '_string')
    server.serve_forever(  )

And here is a client that accesses the server you just wrote:

# server coder sxr_client.py
# needs Python 2.2 or the XML-RPC package from PythonWare

import xmlrpclib

server = xmlrpclib.Server('http://localhost:8000')
print server.chop_in_half('I am a confidant guy')
print server.repeat('Repetition is the key to learning!\n', 5)
print server._string('<= underscore')
print server.python_string.join(['I', 'like it!'], " don't ")
print server._privateFunction(  )    # will throw an exception

Discussion

This ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata