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