2006-02-09

Python web service

In my previous post, I have discussed using Perl (SoapLite) as client to consume a web service implemented using Java(Apache Axis). I am curious to find how it will work out for other lanuages such as Python and Ruby. Here is my try for Python.

The tool I use is ZSI which stands for Zolera SOAP Infrastructure. It provides a tool wsdl2py that can generate Python stub code from a wsdl file. Run the tool on the wsdl file described in my previous post, I get two Python modules: MessageRouter_services_types.py and MessageRouter_services.py. With the help of these two modules, consuming a web service is straight forward. Here is the code:

def sendTo(destination, payload):

loc = MessageRoutingServiceLocator()
kw = { 'tracefile' : sys.stdout }
portType = loc.getMessageRouterPortType(**kw)

dest = ns1.DestinationType_Def()
dest._protocol = "http"
dest._category = "post"
dest._server = "127.0.0.1"
dest._port = 80
dest._target = "/router"

msg = ns1.MessageBodyType_Def()
msg._content = "payload"

req = RouteRequestWrapper()
req._destination = dest
req._request = msg

try:
response = portType.RouteMessage(req)._response._content
print "Response message is:\n %s" % response
except Exception, e:
response = repr(e)
print "Failed: ", e
raise e