Home

Who are we

Articles

SOAP - A Quick Intro to Webservices

XML-RPC - A Five-Minute Tutorial

Installing Apache2 and mod_perl (Windows XP)

Links

Untitled Document

A Python XML-RPC Server

Now for the same in Python. The module SimpleXMLRPCServer is part of the standard Python distribution.

 
dateInfoServer.py
 
#! /usr/bin/python
import sys, time
import SimpleXMLRPCServer

class Date:
    def _dispatch(self, method, params):
        if (method == "Date.dateInfo"):
            return self.dateInfo(*params)
        else:
            return ["Error - unrecognized method"]
        
    def dateInfo(self, option) :
        tm = time.localtime()
        year = tm.tm_year
        month = tm.tm_mon
        day = tm.tm_mday
        hour = tm.tm_hour
        min = tm.tm_min
        sec = tm.tm_sec
        
        if (option == "date"):
            return ["%02d/%02d/%04d" % (month, day, year)]
        elif (option == "time"):
            return ["%02d:%02d:%02d" % (hour, min, sec)]
        elif (option == "all"):
            return ["%02d/%02d/%04d" % (month, day, year),
                "%02d:%02d:%02d" % (hour, min, sec)]
        else:
            return "Error - unrecognized option"
        
        
server = SimpleXMLRPCServer.SimpleXMLRPCServer(
  ("localhost", 9000))
server.register_instance(Date())
server.serve_forever()

SimpleXMLRPCServer creates an instance of the server and register_instance() registers methods in the class Date with the server. Finally serve_forever() tells the server to keep listening for requests.

Now start the Python server and run the perl client. You should get the same result as when using the Perl client. To stop the client hit Ctrl-Break on windows.

A Python XML-RPC Client

Next is the Python client. xmlrpclib is again part of standard Python so everything should work right out of the box:

 
dateInfoClient.py
 
#! /usr/bin/python
import sys
import xmlrpclib

option = sys.argv[1]

# Create an object to represent our server.
server_url = 'http://localhost:9000'
server = xmlrpclib.ServerProxy(server_url)

# Call the server and get our result.
response = server.Date.dateInfo(option)

# read out the response
if (response == None):
    print "Call returned error."
    sys.exit(1)

if (option == "date"):
    print "Current server date is " + response[0]
elif (option == "time"):
    print "Current server time is " + response[0]
elif (option == "all"):
    print "Currently server date is " + response[0]
    print "Currently server time is " + response[1]

The main lines here are xmlrpclib.ServerProxy(), which creates a representation (proxy) of the server and then the direct call to Date.dateInfo() using that server proxy. The rest of the code again is just setting this up and processing the response.

Try the client with the Python and Perl servers and verify that it works in both cases.

Previous - XML-RPC Implementations