Subsections

13. How to create an XML-RPC server with CherryPy

Writing an XML-RPC service with CherryPy is very easy. It works very much the same way as a regular web service. It is base on the xmlrpclib module. This module is included with Python-2.2 and higher, but if you use a lower version, you'll have to download it from http://www.pythonware.com.

All you have to do is add the keyword xmlrpc after the definition of the mask or view, and before the colon. Now, that view or mask will be available to XML-RPC requests.

13.1 Basic Example

Let's take an example. Just create a file called testXmlRpc.cpy containing the following code:

CherryClass Root:
view:
    def add(self, a, b, c) xmlrpc:
        # Return the sum of three numbers
        return a+b+c

CherryClass Xml_rpc:
view:
    def reverse(self, label) xmlrpc:
        # Reverse the characters of a string
        newStr=''
        for i in range(len(label)-1,-1,-1):
            newStr+=label[i]
        return newStr

Also, create a configuration file (textXmlRpcServer.cfg) to tell the server to accept XML-RPC requests:

[server]
typeOfRequests=xmlRpc,web

Compile the source file and start the server: you have an XML-RPC server running.

Now let's write a client. Just create a file called testXmlRpcClient.py containing the following code:

import xmlrpclib
testsvr = xmlrpclib.Server("http://localhost:8000")
print testsvr.add(1,2,3)
print testsvr.xml.rpc.reverse("I love cherry pie")

Run the client and you should see:

[remi@serveur]$ python xmlrpcTestClient.py
6
eip yrrehc evol I
[remi@serveur]$

13.2 Multiple Servers

CherryPy lets you define your XML-RPC server URIs any way you want. In our example client above, we used:

testsvr = xmlrpclib.Server("http://localhost:8000")
print testsvr.xml.rpc.reverse("I love cherry pie")

However, either of the following would work just as well.

testsvr = xmlrpclib.Server("http://localhost:8000/xml")
print testsvr.rpc.reverse("I love cherry pie")

or

testsvr = xmlrpclib.Server("http://localhost:8000/xml/rpc")
print testsvr.reverse("I love cherry pie")

Note that in these two examples, the add view in the Root CherryClass would not be available to the XML-RPC client. This gives you the flexibility to define your XML-RPC APIs to make different methods available at different URIs.

PS: Note that you can also declare a whole CherryClass as xmlrpc. This is equivalent to declaring each mask and view of this CherryClass as xmlrpc. For instance, the basic example of this HowTo could have been written as:

CherryClass Root xmlrpc:
view:
    def add(self, a, b, c):
        # Return the sum of three numbers
        return a+b+c

CherryClass Xml_rpc xmlrpc:
view:
    def reverse(self, label):
        # Reverse the characters of a string
        newStr=''
        for i in range(len(label)-1,-1,-1):
            newStr+=label[i]
        return newStr

See About this document... for information on suggesting changes.