OldStory/Home Linux
XML-RPC servers for Python
by Alnilam
2009. 6. 4.
XML-RPC servers
Python also comes with
SimpleXMLRPCServer
, a module for implementing XML-RPC servers. You can register functions or instances with an instance of the
SimpleXMLRPCServer
class in the module of the same name, in order to expose XML-RPC services. The most straightforward way is to just write an instance with methods that do what you need, and then register this instance. However, in this case, method names cannot have periods, and so the trickery we discussed above to make things appear as if there are multiple objects represented by the server is unavailable. The effect of this will become clear soon, but first of all, let us create a calendar server such as the one we've been using to demonstrate SOAP servers.
Listing 4 (calserver.py) is the XML-RPC calendar server implementation:
import calendar, SimpleXMLRPCServer
#The server object
class Calendar:
def getMonth(self, year, month):
return calendar.month(year, month)
def getYear(self, year):
return calendar.calendar(year)
calendar_object = Calendar()
server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8888))
server.register_instance(calendar_object)
#Go into the main listener loop
print "Listening on port 8888"
server.serve_forever()
|
The class
Calendar
implements the methods we wish to expose. They take numbers and return strings. We create an instance of this object and then an instance of the XML-RPC server class, with which we register the calendar instance. This now makes the methods
getMonth
and
getYear
available on the server. Remember that Python is dynamically typed, and that you will want to add type-checking code to the methods in most cases. Of course Python's rich expressiveness makes this a breeze, and also means that you can easily do more sophisticated type checking than most languages allow. In the main code, we create a server object, giving it a tuple representing the listening address and port. The address can be a host name or IP address. Finally, we put this server into its main loop, which is only broken when an operating system signal interrupts it, such as when the user presses CTRL-C. Open up a separate console and run the server script.
To test the server, we write a simple client in
Listing 5 (calclient.py):
import xmlrpclib
server = xmlrpclib.ServerProxy("http://localhost:8888")
month = server.getMonth(2002, 8 )
print month
|
And here you can see the effect of our not having a period in the method names. Rather than first of all obtaining a pseudo-object from the server (which really just represents an abstraction of the part of the method name before the period), we simply call the method on the server proxy itself. The resulting output is:
$ python calclient.py
August 2002
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
|
From:
http://www.ibm.com/developerworks/library/ws-pyth10.html