# Creating XML-RPC Servers and Clients with Twisted

## Introduction

XML-RPC is a simple request/reply protocol that runs over HTTP. It is simple, easy to implement and supported by most computer languages. Twisted's XML-RPC support uses the xmlrpclib library for parsing - it's included with Python 2.2, but can be downloaded for Python 2.1 from Pythonware.

## Creating a XML-RPC server

Making a server is very easy - all you need to do is inherit from `twisted.web.xmlrpc.XMLRPC`. You then create methods beginning with `xmlrpc_`. The methods' arguments determine what arguments it will accept from XML-RPC clients. The result is what will be returned to the clients.

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 occured, or `twisted.web.xmlrpc.Binary`, `twisted.web.xmlrpc.Boolean` or `twisted.web.xmlrpc.DateTime` instances (all of these are the same as the respective classes in xmlrpclib. In addition, XML-RPC published methods can return `twisted.python.defer.Deferred` 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 Deferred documentation for more details.

`XMLRPC` instances are Resource objects, and they can thus be published using a Site. The following example has two methods published via XML-RPC, `add(a, b)` and `echo(x)`. You can run it directly or with `twistd -y script.py`

    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

    def main():
        from twisted.internet.app import Application
        app = Application("xmlrpc")
        r = Example()
        app.listenTCP(7080, server.Site(r))
        return app

    application = main()

    if __name__ == '__main__':
        application.run(save=0)

After we run this command, we can connect with a client and send commands to the server:

    >>> import xmlrpclib
    >>> s = xmlrpclib.Server('http://localhost:7080/')
    >>> s.echo("lala")
    'lala'
    >>> s.add(1, 2)
    3

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:

    from twisted.web import xmlrpc
    from TwistedQuotes import quoters
    import os

    quotefile = os.path.join(os.path.split(__file__)[0], "quotes.txt")
    quoter = quoters.FortuneQuoter([quotefile])

    class Quoter(xmlrpc.XMLRPC):

        def xmlrpc_quote(self):
            return quoter.getQuote()

    resource = Quoter()

Source listing - listings/TwistedQuotes/xmlquote.rpy

## SOAP Support

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:

    from twisted.web import soap
    from TwistedQuotes import quoters
    import os

    quotefile = os.path.join(os.path.split(__file__)[0], "quotes.txt")
    quoter = quoters.FortuneQuoter([quotefile])

    class Quoter(soap.SOAPPublisher):
        """Publish two methods, 'add' and 'echo'."""

        def soap_quote(self):
            return quoter.getQuote()

    resource = Quoter()

Source listing - listings/TwistedQuotes/soap.rpy

## Creating an XML-RPC Client

XML-RPC clients in Twisted are meant to look as something which will be familiar either to `xmlrpclib` or to Perspective Broker users, taking features from both, as appropriate. There are two major deviations from the `xmlrpclib` way which should be noted:

1. No implicit `/RPC2`. If the services uses this path for the XML-RPC calls, then it will have to be given explicitly.
2. No magic `__getattr__`: calls must be made by an explicit `callMethod`.

The interface Twisted presents to XML-RPC client is that of a proxy object: `twisted.web.xmlrpc.Proxy`. 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.

Having a proxy object, one can just call the `callMethod` 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 cauled. The exception will be the relevant Twisted error in the case of a problem with the underlying connection (for example, a timeout), `IOError` containing the status and message in the case of a non-200 status or a `xmlrpclib.Fault` in the case of an XML-RPC level problem.

    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()

prints:

    [8, 15]

Index