blob: 82ce1da7370c07e456216b5de47fe6854cd2d80d [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`xmlrpclib` --- XML-RPC client access
2==========================================
3
4.. module:: xmlrpclib
5 :synopsis: XML-RPC client access.
6.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
7.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
8
9
Christian Heimes5b5e81c2007-12-31 16:14:33 +000010.. XXX Not everything is documented yet. It might be good to describe
11 Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
14transport. With it, a client can call methods with parameters on a remote
15server (the server is named by a URI) and get back structured data. This module
16supports writing XML-RPC client code; it handles all the details of translating
17between conformable Python objects and XML on the wire.
18
19
20.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]])
21
22 A :class:`ServerProxy` instance is an object that manages communication with a
23 remote XML-RPC server. The required first argument is a URI (Uniform Resource
24 Indicator), and will normally be the URL of the server. The optional second
25 argument is a transport factory instance; by default it is an internal
26 :class:`SafeTransport` instance for https: URLs and an internal HTTP
27 :class:`Transport` instance otherwise. The optional third argument is an
28 encoding, by default UTF-8. The optional fourth argument is a debugging flag.
29 If *allow_none* is true, the Python constant ``None`` will be translated into
30 XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
31 a commonly-used extension to the XML-RPC specification, but isn't supported by
32 all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
33 description. The *use_datetime* flag can be used to cause date/time values to
34 be presented as :class:`datetime.datetime` objects; this is false by default.
35 :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time`
36 objects may be passed to calls. :class:`datetime.date` objects are converted
37 with a time of "00:00:00". :class:`datetime.time` objects are converted using
38 today's date.
39
40 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
41 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
42 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
43 the remote server as part of the connection process when invoking an XML-RPC
44 method. You only need to use this if the remote server requires a Basic
45 Authentication user and password.
46
47 The returned instance is a proxy object with methods that can be used to invoke
48 corresponding RPC calls on the remote server. If the remote server supports the
49 introspection API, the proxy can also be used to query the remote server for the
50 methods it supports (service discovery) and fetch other server-associated
51 metadata.
52
53 :class:`ServerProxy` instance methods take Python basic types and objects as
54 arguments and return Python basic types and classes. Types that are conformable
55 (e.g. that can be marshalled through XML), include the following (and except
56 where noted, they are unmarshalled as the same Python type):
57
58 +---------------------------------+---------------------------------------------+
59 | Name | Meaning |
60 +=================================+=============================================+
61 | :const:`boolean` | The :const:`True` and :const:`False` |
62 | | constants |
63 +---------------------------------+---------------------------------------------+
64 | :const:`integers` | Pass in directly |
65 +---------------------------------+---------------------------------------------+
66 | :const:`floating-point numbers` | Pass in directly |
67 +---------------------------------+---------------------------------------------+
68 | :const:`strings` | Pass in directly |
69 +---------------------------------+---------------------------------------------+
70 | :const:`arrays` | Any Python sequence type containing |
71 | | conformable elements. Arrays are returned |
72 | | as lists |
73 +---------------------------------+---------------------------------------------+
74 | :const:`structures` | A Python dictionary. Keys must be strings, |
75 | | values may be any conformable type. Objects |
76 | | of user-defined classes can be passed in; |
77 | | only their *__dict__* attribute is |
78 | | transmitted. |
79 +---------------------------------+---------------------------------------------+
80 | :const:`dates` | in seconds since the epoch (pass in an |
81 | | instance of the :class:`DateTime` class) or |
82 | | a :class:`datetime.datetime`, |
83 | | :class:`datetime.date` or |
84 | | :class:`datetime.time` instance |
85 +---------------------------------+---------------------------------------------+
86 | :const:`binary data` | pass in an instance of the :class:`Binary` |
87 | | wrapper class |
88 +---------------------------------+---------------------------------------------+
89
90 This is the full set of data types supported by XML-RPC. Method calls may also
91 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
92 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
93 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
94 :exc:`Error`. Note that even though starting with Python 2.2 you can subclass
95 builtin types, the xmlrpclib module currently does not marshal instances of such
96 subclasses.
97
98 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
99 will be automatically escaped. However, it's the caller's responsibility to
100 ensure that the string is free of characters that aren't allowed in XML, such as
101 the control characters with ASCII values between 0 and 31 (except, of course,
102 tab, newline and carriage return); failing to do this will result in an XML-RPC
103 request that isn't well-formed XML. If you have to pass arbitrary strings via
104 XML-RPC, use the :class:`Binary` wrapper class described below.
105
106 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
107 compatibility. New code should use :class:`ServerProxy`.
108
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110.. seealso::
111
112 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000113 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000114 Contains pretty much everything an XML-RPC client developer needs to know.
115
Christian Heimesa62da1d2008-01-12 19:39:10 +0000116 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
117 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119
120.. _serverproxy-objects:
121
122ServerProxy Objects
123-------------------
124
125A :class:`ServerProxy` instance has a method corresponding to each remote
126procedure call accepted by the XML-RPC server. Calling the method performs an
127RPC, dispatched by both name and argument signature (e.g. the same method name
128can be overloaded with multiple argument signatures). The RPC finishes by
129returning a value, which may be either returned data in a conformant type or a
130:class:`Fault` or :class:`ProtocolError` object indicating an error.
131
132Servers that support the XML introspection API support some common methods
133grouped under the reserved :attr:`system` member:
134
135
136.. method:: ServerProxy.system.listMethods()
137
138 This method returns a list of strings, one for each (non-system) method
139 supported by the XML-RPC server.
140
141
142.. method:: ServerProxy.system.methodSignature(name)
143
144 This method takes one parameter, the name of a method implemented by the XML-RPC
145 server.It returns an array of possible signatures for this method. A signature
146 is an array of types. The first of these types is the return type of the method,
147 the rest are parameters.
148
149 Because multiple signatures (ie. overloading) is permitted, this method returns
150 a list of signatures rather than a singleton.
151
152 Signatures themselves are restricted to the top level parameters expected by a
153 method. For instance if a method expects one array of structs as a parameter,
154 and it returns a string, its signature is simply "string, array". If it expects
155 three integers and returns a string, its signature is "string, int, int, int".
156
157 If no signature is defined for the method, a non-array value is returned. In
158 Python this means that the type of the returned value will be something other
159 that list.
160
161
162.. method:: ServerProxy.system.methodHelp(name)
163
164 This method takes one parameter, the name of a method implemented by the XML-RPC
165 server. It returns a documentation string describing the use of that method. If
166 no such string is available, an empty string is returned. The documentation
167 string may contain HTML markup.
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170.. _boolean-objects:
171
172Boolean Objects
173---------------
174
175This class may be initialized from any Python value; the instance returned
176depends only on its truth value. It supports various Python operators through
177:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__bool__`
178methods, all implemented in the obvious ways.
179
180It also has the following method, supported mainly for internal use by the
181unmarshalling code:
182
183
184.. method:: Boolean.encode(out)
185
186 Write the XML-RPC encoding of this Boolean item to the out stream object.
187
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000188A working example follows. The server code::
189
190 import xmlrpclib
191 from SimpleXMLRPCServer import SimpleXMLRPCServer
192
193 def is_even(n):
194 return n%2 == 0
195
196 server = SimpleXMLRPCServer(("localhost", 8000))
197 print "Listening on port 8000..."
198 server.register_function(is_even, "is_even")
199 server.serve_forever()
200
201The client code for the preceding server::
202
203 import xmlrpclib
204
205 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
206 print "3 is even: %s" % str(proxy.is_even(3))
207 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209.. _datetime-objects:
210
211DateTime Objects
212----------------
213
214This class may be initialized with seconds since the epoch, a time tuple, an ISO
2158601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
216or :class:`datetime.time` instance. It has the following methods, supported
217mainly for internal use by the marshalling/unmarshalling code:
218
219
220.. method:: DateTime.decode(string)
221
222 Accept a string as the instance's new time value.
223
224
225.. method:: DateTime.encode(out)
226
227 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
228 object.
229
230It also supports certain of Python's built-in operators through :meth:`__cmp__`
231and :meth:`__repr__` methods.
232
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000233A working example follows. The server code::
234
235 import datetime
236 from SimpleXMLRPCServer import SimpleXMLRPCServer
237 import xmlrpclib
238
239 def today():
240 today = datetime.datetime.today()
241 return xmlrpclib.DateTime(today)
242
243 server = SimpleXMLRPCServer(("localhost", 8000))
244 print "Listening on port 8000..."
245 server.register_function(today, "today")
246 server.serve_forever()
247
248The client code for the preceding server::
249
250 import xmlrpclib
251 import datetime
252
253 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
254
255 today = proxy.today()
256 # convert the ISO8601 string to a datetime object
257 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
258 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260.. _binary-objects:
261
262Binary Objects
263--------------
264
265This class may be initialized from string data (which may include NULs). The
266primary access to the content of a :class:`Binary` object is provided by an
267attribute:
268
269
270.. attribute:: Binary.data
271
272 The binary data encapsulated by the :class:`Binary` instance. The data is
273 provided as an 8-bit string.
274
275:class:`Binary` objects have the following methods, supported mainly for
276internal use by the marshalling/unmarshalling code:
277
278
279.. method:: Binary.decode(string)
280
281 Accept a base64 string and decode it as the instance's new data.
282
283
284.. method:: Binary.encode(out)
285
286 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
287
288It also supports certain of Python's built-in operators through a
289:meth:`__cmp__` method.
290
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000291Example usage of the binary objects. We're going to transfer an image over
292XMLRPC::
293
294 from SimpleXMLRPCServer import SimpleXMLRPCServer
295 import xmlrpclib
296
297 def python_logo():
298 handle = open("python_logo.jpg")
299 return xmlrpclib.Binary(handle.read())
300 handle.close()
301
302 server = SimpleXMLRPCServer(("localhost", 8000))
303 print "Listening on port 8000..."
304 server.register_function(python_logo, 'python_logo')
305
306 server.serve_forever()
307
308The client gets the image and saves it to a file::
309
310 import xmlrpclib
311
312 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
313 handle = open("fetched_python_logo.jpg", "w")
314 handle.write(proxy.python_logo().data)
315 handle.close()
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317.. _fault-objects:
318
319Fault Objects
320-------------
321
322A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
323objects have the following members:
324
325
326.. attribute:: Fault.faultCode
327
328 A string indicating the fault type.
329
330
331.. attribute:: Fault.faultString
332
333 A string containing a diagnostic message associated with the fault.
334
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000335In the following example we're going to intentionally cause a :exc:`Fault` by
336returning a complex type object. The server code::
337
338 from SimpleXMLRPCServer import SimpleXMLRPCServer
339
340 # A marshalling error is going to occur because we're returning a
341 # complex number
342 def add(x,y):
343 return x+y+0j
344
345 server = SimpleXMLRPCServer(("localhost", 8000))
346 print "Listening on port 8000..."
347 server.register_function(add, 'add')
348
349 server.serve_forever()
350
351The client code for the preceding server::
352
353 import xmlrpclib
354
355 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
356 try:
357 proxy.add(2, 5)
358 except xmlrpclib.Fault, err:
359 print "A fault occured"
360 print "Fault code: %d" % err.faultCode
361 print "Fault string: %s" % err.faultString
362
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365.. _protocol-error-objects:
366
367ProtocolError Objects
368---------------------
369
370A :class:`ProtocolError` object describes a protocol error in the underlying
371transport layer (such as a 404 'not found' error if the server named by the URI
372does not exist). It has the following members:
373
374
375.. attribute:: ProtocolError.url
376
377 The URI or URL that triggered the error.
378
379
380.. attribute:: ProtocolError.errcode
381
382 The error code.
383
384
385.. attribute:: ProtocolError.errmsg
386
387 The error message or diagnostic string.
388
389
390.. attribute:: ProtocolError.headers
391
Guido van Rossum460add42007-08-23 02:13:35 +0000392 A dict containing the headers of the HTTP/HTTPS request that triggered the
Georg Brandl116aa622007-08-15 14:28:22 +0000393 error.
394
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000395In the following example we're going to intentionally cause a :exc:`ProtocolError`
396by providing an invalid URI::
397
398 import xmlrpclib
399
400 # create a ServerProxy with an invalid URI
401 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
402
403 try:
404 proxy.some_method()
405 except xmlrpclib.ProtocolError, err:
406 print "A protocol error occured"
407 print "URL: %s" % err.url
408 print "HTTP/HTTPS headers: %s" % err.headers
409 print "Error code: %d" % err.errcode
410 print "Error message: %s" % err.errmsg
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412MultiCall Objects
413-----------------
414
Georg Brandl116aa622007-08-15 14:28:22 +0000415In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
416encapsulate multiple calls to a remote server into a single request.
417
418
419.. class:: MultiCall(server)
420
421 Create an object used to boxcar method calls. *server* is the eventual target of
422 the call. Calls can be made to the result object, but they will immediately
423 return ``None``, and only store the call name and parameters in the
424 :class:`MultiCall` object. Calling the object itself causes all stored calls to
425 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000426 is a :term:`generator`; iterating over this generator yields the individual
427 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000429A usage example of this class follows. The server code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000431 from SimpleXMLRPCServer import SimpleXMLRPCServer
432
433 def add(x,y):
434 return x+y
435
436 def subtract(x, y):
437 return x-y
438
439 def multiply(x, y):
440 return x*y
441
442 def divide(x, y):
443 return x/y
444
445 # A simple server with simple arithmetic functions
446 server = SimpleXMLRPCServer(("localhost", 8000))
447 print "Listening on port 8000..."
448 server.register_multicall_functions()
449 server.register_function(add, 'add')
450 server.register_function(subtract, 'subtract')
451 server.register_function(multiply, 'multiply')
452 server.register_function(divide, 'divide')
453 server.serve_forever()
454
455The client code for the preceding server::
456
457 import xmlrpclib
458
459 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
460 multicall = xmlrpclib.MultiCall(proxy)
461 multicall.add(7,3)
462 multicall.subtract(7,3)
463 multicall.multiply(7,3)
464 multicall.divide(7,3)
465 result = multicall()
466
467 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl116aa622007-08-15 14:28:22 +0000468
469
470Convenience Functions
471---------------------
472
473
474.. function:: boolean(value)
475
476 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
477 ``False``.
478
479
480.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
481
482 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
483 is true. *params* can be either a tuple of arguments or an instance of the
484 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
485 can be returned, meaning that *params* must be of length 1. *encoding*, if
486 supplied, is the encoding to use in the generated XML; the default is UTF-8.
487 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
488 it via an extension, provide a true value for *allow_none*.
489
490
491.. function:: loads(data[, use_datetime])
492
493 Convert an XML-RPC request or response into Python objects, a ``(params,
494 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
495 ``None`` if no method name is present in the packet. If the XML-RPC packet
496 represents a fault condition, this function will raise a :exc:`Fault` exception.
497 The *use_datetime* flag can be used to cause date/time values to be presented as
498 :class:`datetime.datetime` objects; this is false by default. Note that even if
499 you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
500 objects, they are converted to :class:`DateTime` objects internally, so only
501 :class:`datetime.datetime` objects will be returned.
502
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504.. _xmlrpc-client-example:
505
506Example of Client Usage
507-----------------------
508
509::
510
511 # simple test program (from the XML-RPC specification)
512 from xmlrpclib import ServerProxy, Error
513
514 # server = ServerProxy("http://localhost:8000") # local server
515 server = ServerProxy("http://betty.userland.com")
516
Collin Winterc79461b2007-09-01 23:34:30 +0000517 print(server)
Georg Brandl116aa622007-08-15 14:28:22 +0000518
519 try:
Collin Winterc79461b2007-09-01 23:34:30 +0000520 print(server.examples.getStateName(41))
Georg Brandl116aa622007-08-15 14:28:22 +0000521 except Error as v:
Collin Winterc79461b2007-09-01 23:34:30 +0000522 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524To access an XML-RPC server through a proxy, you need to define a custom
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000525transport. The following example shows how:
Georg Brandl116aa622007-08-15 14:28:22 +0000526
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000527.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529::
530
531 import xmlrpclib, httplib
532
533 class ProxiedTransport(xmlrpclib.Transport):
534 def set_proxy(self, proxy):
535 self.proxy = proxy
536 def make_connection(self, host):
537 self.realhost = host
538 h = httplib.HTTP(self.proxy)
539 return h
540 def send_request(self, connection, handler, request_body):
541 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
542 def send_host(self, connection, host):
543 connection.putheader('Host', self.realhost)
544
545 p = ProxiedTransport()
546 p.set_proxy('proxy-server:8080')
547 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
Collin Winterc79461b2007-09-01 23:34:30 +0000548 print(server.currentTime.getCurrentTime())
Georg Brandl116aa622007-08-15 14:28:22 +0000549
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000550
551Example of Client and Server Usage
552----------------------------------
553
554See :ref:`simplexmlrpcserver-example`.
555
556