Yes folks, Python is truly a programmer's goldmine. Today we're going to do something Web 2.0-worthy with Python. We're going to create a server written in Python. But not just any old server. We're going to create an XML-RPC server, and we'll also write up a tiny client for it as well to demonstrate how surprisingly simple it is to build a server.
First, let's write up the server itself. Let's call this file "xmlrpc_server.py":
#!/usr/bin/env python
import SimpleXMLRPCServer
#set server address(local here)
servAddr=("localhost",8080)
#define server functions and instances here
def areaSquare(length):
return length*length
def areaRectangle(length,width):
return length*width
def areaCircle(radius):
return 3.14*(radius*radius)
class MyFuncs:
def say(self,line):
return "#"+line+"#"
#create the server object
server=SimpleXMLRPCServer.SimpleXMLRPCServer(servAddr)
funclist=(areaSquare,areaRectangle,areaCircle)
#register functions
for eachfunc in funclist:
server.register_function(eachfunc)
#register instance
server.register_instance(MyFuncs())
server.register_introspection_functions()
#start serving
server.serve_forever()
To start up this little server, type "python ./xmlrpc_server.py
&" on the command-line. Now, let's write a little demo client
to show that we can actually use the server. This file will be
called "xmlrpc_client.py":
#!/usr/bin/env python
import xmlrpclib
#connect to a server
servAddr="http://localhost:8080"
s=xmlrpclib.ServerProxy(servAddr)
#list available server methods
for m in s.system.listMethods():
print m
#call server methods
print "Areas:"
print "Square:",s.areaSquare(5)
print "Rectangle:",s.areaRectangle(2,6)
print "Circle:",s.areaCircle(5)
print s.say("E=m(c*c)")
Simply run "python ./xmlrpc_client.py", and you'll see that we are
actually using functions stored remotely on the server. Pretty
cool, right? No? Well, you haven't seen anything yet. You see, this
XML-RPC stuff can be used within web services, which shockingly
includes scripted objects within Second Life. With XML-RPC you can
create objects networked together to do things that would be
difficult, slow, or plain impossible to implement. I'll get more
into this in my next post.