<?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Creating XML-RPC Servers and Clients with Twisted</title> </head> <body> <h1>Creating XML-RPC Servers and Clients with Twisted</h1> <h2>Introduction</h2> <p><a href="http://www.xmlrpc.com">XML-RPC</a> is a simple request/reply protocol that runs over HTTP. It is simple, easy to implement and supported by most programming languages. Twisted's XML-RPC support is implemented using the xmlrpclib library that is included with Python 2.2 and later.</p> <h2>Creating a XML-RPC server</h2> <p>Making a server is very easy - all you need to do is inherit from <code class="API">twisted.web.xmlrpc.XMLRPC</code>. You then create methods beginning with <code>xmlrpc_</code>. The methods' arguments determine what arguments it will accept from XML-RPC clients. The result is what will be returned to the clients.</p> <p>Methods published via XML-RPC can return all the basic XML-RPC types, such as strings, lists and so on (just return a regular python integer, etc). They can also return Failure instances to indicate an error has occurred, or <code base="twisted.web.xmlrpc" class="API">Binary</code>, <code base="twisted.web.xmlrpc" class="API">Boolean</code> or <code base="twisted.web.xmlrpc" class="API">DateTime</code> instances (all of these are the same as the respective classes in xmlrpclib. In addition, XML-RPC published methods can return <code base="twisted.internet.defer" class="API">Deferred</code> instances whose results are one of the above. This allows you to return results that can't be calculated immediately, such as database queries. See the <a href="defer.xhtml">Deferred documentation</a> for more details.</p> <p><code base="twisted.web.xmlrpc" class="API">XMLRPC</code> instances are Resource objects, and they can thus be published using a Site. The following example has two methods published via XML-RPC, <code>add(a, b)</code> and <code>echo(x)</code>.</p> <pre class="python"> from twisted.web import xmlrpc, server class Example(xmlrpc.XMLRPC): """An example object to be published.""" def xmlrpc_echo(self, x): """Return all passed args.""" return x def xmlrpc_add(self, a, b): """Return sum of arguments.""" return a + b if __name__ == '__main__': from twisted.internet import reactor r = Example() reactor.listenTCP(7080, server.Site(r)) reactor.run() </pre> <p>After we run this command, we can connect with a client and send commands to the server:</p> <pre class="python-interpreter"> >>> import xmlrpclib >>> s = xmlrpclib.Server('http://localhost:7080/') >>> s.echo("lala") 'lala' >>> s.add(1, 2) 3 </pre> <p>XML-RPC resources can also be part of a normal Twisted web server, using resource scripts. The following is an example of such a resource script:</p> <a href="listings/TwistedQuotes/xmlquote.rpy" class="py-listing">xmlquote.rpy</a> <h3>Using XML-RPC sub-handlers</h3> <p>XML-RPC resource can be nested so that one handler calls another if a method with a given prefix is called. For example, to add support for an XML-RPC method <code>date.time()</code> to the <code class="python">Example</code> class, you could do the following:</p> <pre class="python"> import time from twisted.web import xmlrpc, server class Example(xmlrpc.XMLRPC): """An example object to be published.""" def xmlrpc_echo(self, x): """Return all passed args.""" return x def xmlrpc_add(self, a, b): """Return sum of arguments.""" return a + b class Date(xmlrpc.XMLRPC): """Serve the XML-RPC 'time' method.""" def xmlrpc_time(self): """Return UNIX time.""" return time.time() if __name__ == '__main__': from twisted.internet import reactor r = Example() date = Date() r.putSubHandler('date', date) reactor.listenTCP(7080, server.Site(r)) reactor.run() </pre> <p>By default, a period ('.') separates the prefix from the method name, but you can use a different character by overriding the <code class="python">XMLRPC.separator</code> data member in your base XML-RPC server. XML-RPC servers may be nested to arbitrary depths using this method.</p> <h3>Adding XML-RPC Introspection support</h3> <p>XML-RPC has an informal <a href="http://ldp.kernelnotes.de/HOWTO/XML-RPC-HOWTO/xmlrpc-howto-interfaces.html">Introspection API</a> that specifies three methods in a <code>system</code> sub-handler which allow a client to query a server about the server's API. Adding Introspection support to the <code class="python">Example</code> class is easy using the <code base="twisted.web.xmlrpc" class="API">XMLRPCIntrospection</code> class:</p> <pre class="python"> from twisted.web import xmlrpc, server class Example(xmlrpc.XMLRPC): """An example object to be published.""" def xmlrpc_echo(self, x): """Return all passed args.""" return x xmlrpc_echo.signature = [['string', 'string'], ['int', 'int'], ['double', 'double'], ['array', 'array'], ['struct', 'struct']] def xmlrpc_add(self, a, b): """Return sum of arguments.""" return a + b xmlrpc_add.signature = [['int', 'int', 'int'], ['double', 'double', 'double']] xmlrpc_add.help = "Add the arguments and return the sum." if __name__ == '__main__': from twisted.internet import reactor r = Example() xmlrpc.addIntrospection(r) reactor.listenTCP(7080, server.Site(r)) reactor.run() </pre> <p>Note the method attributes <code class="python">help</code> and <code class="python">signature</code> which are used by the Introspection API methods <code>system.methodHelp</code> and <code>system.methodSignature</code> respectively. If no <code class="python">help</code> attribute is specified, the method's documentation string is used instead.</p> <h2>SOAP Support</h2> <p>From the point of view of a Twisted developer, there is little difference between XML-RPC support and SOAP support. Here is an example of SOAP usage:</p> <a href="listings/TwistedQuotes/soap.rpy" class="py-listing">soap.rpy</a> <h2>Creating an XML-RPC Client</h2> <p>XML-RPC clients in Twisted are meant to look as something which will be familiar either to <code>xmlrpclib</code> or to Perspective Broker users, taking features from both, as appropriate. There are two major deviations from the <code>xmlrpclib</code> way which should be noted:</p> <ol> <li>No implicit <code>/RPC2</code>. If the services uses this path for the XML-RPC calls, then it will have to be given explicitly.</li> <li>No magic <code>__getattr__</code>: calls must be made by an explicit <code>callRemote</code>.</li> </ol> <p>The interface Twisted presents to XML-RPC client is that of a proxy object: <code class="API">twisted.web.xmlrpc.Proxy</code>. The constructor for the object receives a URL: it must be an HTTP or HTTPS URL. When an XML-RPC service is described, the URL to that service will be given there.</p> <p>Having a proxy object, one can just call the <code>callRemote</code> method, which accepts a method name and a variable argument list (but no named arguments, as these are not supported by XML-RPC). It returns a deferred, which will be called back with the result. If there is any error, at any level, the errback will be called. The exception will be the relevant Twisted error in the case of a problem with the underlying connection (for example, a timeout), <code>IOError</code> containing the status and message in the case of a non-200 status or a <code>xmlrpclib.Fault</code> in the case of an XML-RPC level problem.</p> <pre class="python"> from twisted.web.xmlrpc import Proxy from twisted.internet import reactor def printValue(value): print repr(value) reactor.stop() def printError(error): print 'error', error reactor.stop() proxy = Proxy('http://advogato.org/XMLRPC') proxy.callRemote('test.sumprod', 3, 5).addCallbacks(printValue, printError) reactor.run() </pre> <p>prints:</p> <pre> [8, 15] </pre> <h2>Serving SOAP and XML-RPC simultaneously</h2> <p><code class="API">twisted.web.xmlrpc.XMLRPC</code> and <code class="API">twisted.web.soap.SOAPPublisher</code> are both <code class="API" base="twisted.web.resource">Resources</code>. So, to serve both XML-RPC and SOAP in the one web server, you can use the <code class="API" base="twisted.web.resource.IResource">putChild</code> method of Resources.</p> <p>The following example uses an empty <code class="API" base="twisted.web">resource.Resource</code> as the root resource for a <code class="API" base="twisted.web.server">Site</code>, and then adds <code>/RPC2</code> and <code>/SOAP</code> paths to it.</p> <a href="listings/TwistedQuotes/xmlAndSoapQuote.py" class="py-listing">xmlAndSoapQuote.py</a> <p>Refer to <a href="using-twistedweb.xhtml#development">Twisted Web Development</a> for more details about Resources.</p> </body> </html>