1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
|
:LastChangedDate: $LastChangedDate$
:LastChangedRevision: $LastChangedRevision$
:LastChangedBy: $LastChangedBy$
Creating XML-RPC Servers and Clients with Twisted
=================================================
Introduction
------------
`XML-RPC <http://www.xmlrpc.com>`_ 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 <http://docs.python.org/library/xmlrpclib.html>`_ library that is
included with Python 2.2 and later.
Creating a XML-RPC server
-------------------------
Making a server is very easy - all you need to do is inherit from :py:class:`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 raise exceptions or return Failure instances to indicate an
error has occurred, or ``Binary`` , ``Boolean`` or ``DateTime``
instances (all of these are the same as the respective classes in xmlrpclib. In
addition, XML-RPC published methods can return :py:class:`Deferred <twisted.internet.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 :doc:`Deferred documentation <../../core/howto/defer>` for more
details.
:py:class:`XMLRPC <twisted.web.xmlrpc.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)`` .
.. code-block:: 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
def xmlrpc_fault(self):
"""
Raise a Fault indicating that the procedure should not be used.
"""
raise xmlrpc.Fault(123, "The fault procedure is faulty.")
if __name__ == '__main__':
from twisted.internet import reactor, endpoints
r = Example()
endpoint = endpoints.TCP4ServerEndpoint(reactor, 7080)
endpoint.listen(server.Site(r))
reactor.run()
After we run this command, we can connect with a client and send commands
to the server:
.. code-block:: pycon
>>> import xmlrpclib
>>> s = xmlrpclib.Server('http://localhost:7080/')
>>> s.echo("lala")
'lala'
>>> s.add(1, 2)
3
>>> s.fault()
Traceback (most recent call last):
...
xmlrpclib.Fault: <Fault 123: 'The fault procedure is faulty.'>
>>>
If the :py:class:`Request <twisted.web.server.Request>` object is
needed by an ``xmlrpc_*`` method, it can be made available using
the :py:func:`twisted.web.xmlrpc.withRequest` decorator. When
using this decorator, the method will be passed the request object as the first
argument, before any XML-RPC parameters. For example:
.. code-block:: python
from twisted.web.xmlrpc import XMLRPC, withRequest
from twisted.web.server import Site
class Example(XMLRPC):
@withRequest
def xmlrpc_headerValue(self, request, headerName):
return request.requestHeaders.getRawHeaders(headerName)
if __name__ == '__main__':
from twisted.internet import reactor, endpoints
endpoint = endpoints.TCP4ServerEndpoint(reactor, 7080)
endpoint.listen(Site(Example()))
reactor.run()
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:
:download:`xmlquote.rpy <listings/xmlquote.rpy>`
.. literalinclude:: listings/xmlquote.rpy
Using XML-RPC sub-handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~
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 ``date.time()`` to
the ``Example`` class, you could do the
following:
.. code-block:: 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, endpoints
r = Example()
date = Date()
r.putSubHandler('date', date)
endpoint = endpoints.TCP4ServerEndpoint(reactor, 7080)
endpoint.listen(server.Site(r))
reactor.run()
By default, a period ('.') separates the prefix from the method
name, but you can use a different character by overriding the ``XMLRPC.separator`` data member in your base
XML-RPC server. XML-RPC servers may be nested to arbitrary depths
using this method.
Using your own procedure getter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes, you want to implement your own policy of getting the end implementation.
E.g. just like sub-handlers you want to divide the implementations into separate classes but
may not want to introduce ``XMLRPC.separator`` in the procedure name.
In such cases just override the ``lookupProcedure(self, procedurePath)``
method and return the correct callable.
Raise :py:class:`twisted.web.xmlrpc.NoSuchFunction` otherwise.
:download:`xmlrpc-customized.py <listings/xmlrpc-customized.py>`
.. literalinclude:: listings/xmlrpc-customized.py
Adding XML-RPC Introspection support
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
XML-RPC has an
informal `IntrospectionAPI <http://tldp.org/HOWTO/XML-RPC-HOWTO/xmlrpc-howto-interfaces.html>`_ that specifies three methods in a ``system``
sub-handler which allow a client to query a server about the server's
API. Adding Introspection support to
the ``Example`` class is easy using
the :py:class:`XMLRPCIntrospection <twisted.web.xmlrpc.XMLRPCIntrospection>` class:
.. code-block:: 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, endpoints
r = Example()
xmlrpc.addIntrospection(r)
endpoint = endpoints.TCP4ServerEndpoint(reactor, 7080)
endpoint.listen(server.Site(r))
reactor.run()
Note the method attributes ``help``
and ``signature`` which are used by the
Introspection API methods ``system.methodHelp``
and ``system.methodSignature`` respectively. If
no ``help`` attribute is specified, the
method's documentation string is used instead.
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:
#. No implicit ``/RPC2`` . If the services uses this path for the
XML-RPC calls, then it will have to be given explicitly.
#. No magic ``__getattr__`` : calls must be made by an explicit
``callRemote`` .
The interface Twisted presents to XML-RPC client is that of a proxy
object: :py:class:`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 ``callRemote`` 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), ``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.
.. code-block:: 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()
prints:
::
[8, 15]
Debugging with an XML-RPC client
--------------------------------
Sometimes an XML-RPC server may send non-standard XML-RPC responses to your
client. In those cases, you can access the raw XML-RPC responses from the
server with :py:mod:`twisted.web.xmlrpc`'s ``QueryFactory``.
You can simply log the response content strings for debugging, or implement
your own custom XML-RPC marshaller to handle the non-standard XML-RPC
responses.
An example Twisted application that does this can be found in
``docs/web/examples/xmlrpc-debug.py`` .
|