Tuesday, November 3, 2009

Creating an XML-RPC Client










Creating an XML-RPC Client






import xmlrpclib
servAddr = "http://localhost:8080"
s = xmlrpclib.ServerProxy(servAddr)
methods = s.system.listMethods()
s.areaSquare(5)
s.areaRectangle(4,5)
s.areaCircle(5)




The xmlrpclib module provided with Python allows you to create clients that can access web services that support the XML-RPC protocol. The XML-RPC protocol uses XML data encoding to transmit remote procedure calls across the HTTP protocol. This section discusses how to use the xmlrpclib module to create a client to access an XML-RPC server.


The first step is to authenticate to the XML-RPC proxy server by calling the ServerProxy(uri [, transport [, encoding [ , verbose [, allow_none]]]]) function. The ServerProxy function connects to the remote location specified by uri and returns an instance of the ServerProxy object.


After you have connected to the XML-RPC server, you can invoke methods on the remote server by calling them as a function of the ServerProject object. For example, you can call the introspection system.listMethods() using the "." syntax shown in the sample code xml-rpc_client.py. The system.listMethods() function returns a list of functions that are available on the XML-RPC server. Other remote functions that are registered on the XML-RPC server are invoked the same way.


import xmlrpclib

servAddr = "http://localhost:8080"

#Attach to XML-RPC server
s = xmlrpclib.ServerProxy(servAddr)

#List Methods
print "Methods\n==============="
methods = s.system.listMethods()
for m in methods:
print m

#Call Methods
print "\nArea\n================"
print "5 in. Square =", s.areaSquare(5)
print "4x5 in. Rectangle =", s.areaRectangle(4,5)
print "10 in. Circle =", s.areaCircle(5)


xml-rpc_client.py


Methods
===============
areaCircle
areaRectangle
areaSquare
system.listMethods
system.methodHelp
system.methodSignature

Area
================
5 in. Square = 25
4x5 in. Rectangle = 20
10 in. Circle = 78.5


Output of xml-rpc_client.py












No comments:

Post a Comment