blob: a227c4728b16841938f435423eb71f7df9a6c052 [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():
321 handle = open("python_logo.jpg")
322 return xmlrpclib.Binary(handle.read())
323 handle.close()
324
325 server = SimpleXMLRPCServer(("localhost", 8000))
326 print "Listening on port 8000..."
327 server.register_function(python_logo, 'python_logo')
328
329 server.serve_forever()
330
331The client gets the image and saves it to a file::
332
333 import xmlrpclib
334
335 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
336 handle = open("fetched_python_logo.jpg", "w")
337 handle.write(proxy.python_logo().data)
338 handle.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339
340.. _fault-objects:
341
342Fault Objects
343-------------
344
345A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
346objects have the following members:
347
348
349.. attribute:: Fault.faultCode
350
351 A string indicating the fault type.
352
353
354.. attribute:: Fault.faultString
355
356 A string containing a diagnostic message associated with the fault.
357
Georg Brandl0a0cf162007-12-03 20:03:46 +0000358In the following example we're going to intentionally cause a :exc:`Fault` by
359returning a complex type object. The server code::
360
361 from SimpleXMLRPCServer import SimpleXMLRPCServer
362
363 # A marshalling error is going to occur because we're returning a
364 # complex number
365 def add(x,y):
366 return x+y+0j
367
368 server = SimpleXMLRPCServer(("localhost", 8000))
369 print "Listening on port 8000..."
370 server.register_function(add, 'add')
371
372 server.serve_forever()
373
374The client code for the preceding server::
375
376 import xmlrpclib
377
378 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
379 try:
380 proxy.add(2, 5)
381 except xmlrpclib.Fault, err:
Benjamin Peterson90f36732008-07-12 20:16:19 +0000382 print "A fault occurred"
Georg Brandl0a0cf162007-12-03 20:03:46 +0000383 print "Fault code: %d" % err.faultCode
384 print "Fault string: %s" % err.faultString
385
386
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387
388.. _protocol-error-objects:
389
390ProtocolError Objects
391---------------------
392
393A :class:`ProtocolError` object describes a protocol error in the underlying
394transport layer (such as a 404 'not found' error if the server named by the URI
395does not exist). It has the following members:
396
397
398.. attribute:: ProtocolError.url
399
400 The URI or URL that triggered the error.
401
402
403.. attribute:: ProtocolError.errcode
404
405 The error code.
406
407
408.. attribute:: ProtocolError.errmsg
409
410 The error message or diagnostic string.
411
412
413.. attribute:: ProtocolError.headers
414
415 A string containing the headers of the HTTP/HTTPS request that triggered the
416 error.
417
Georg Brandl0a0cf162007-12-03 20:03:46 +0000418In the following example we're going to intentionally cause a :exc:`ProtocolError`
419by providing an invalid URI::
420
421 import xmlrpclib
422
423 # create a ServerProxy with an invalid URI
424 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
425
426 try:
427 proxy.some_method()
428 except xmlrpclib.ProtocolError, err:
Benjamin Peterson90f36732008-07-12 20:16:19 +0000429 print "A protocol error occurred"
Georg Brandl0a0cf162007-12-03 20:03:46 +0000430 print "URL: %s" % err.url
431 print "HTTP/HTTPS headers: %s" % err.headers
432 print "Error code: %d" % err.errcode
433 print "Error message: %s" % err.errmsg
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
435MultiCall Objects
436-----------------
437
438.. versionadded:: 2.4
439
440In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
441encapsulate multiple calls to a remote server into a single request.
442
443
444.. class:: MultiCall(server)
445
446 Create an object used to boxcar method calls. *server* is the eventual target of
447 the call. Calls can be made to the result object, but they will immediately
448 return ``None``, and only store the call name and parameters in the
449 :class:`MultiCall` object. Calling the object itself causes all stored calls to
450 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000451 is a :term:`generator`; iterating over this generator yields the individual
452 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000453
Georg Brandl0a0cf162007-12-03 20:03:46 +0000454A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000455
Georg Brandl0a0cf162007-12-03 20:03:46 +0000456 from SimpleXMLRPCServer import SimpleXMLRPCServer
457
458 def add(x,y):
459 return x+y
460
461 def subtract(x, y):
462 return x-y
463
464 def multiply(x, y):
465 return x*y
466
467 def divide(x, y):
468 return x/y
469
470 # A simple server with simple arithmetic functions
471 server = SimpleXMLRPCServer(("localhost", 8000))
472 print "Listening on port 8000..."
473 server.register_multicall_functions()
474 server.register_function(add, 'add')
475 server.register_function(subtract, 'subtract')
476 server.register_function(multiply, 'multiply')
477 server.register_function(divide, 'divide')
478 server.serve_forever()
479
480The client code for the preceding server::
481
482 import xmlrpclib
483
484 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
485 multicall = xmlrpclib.MultiCall(proxy)
486 multicall.add(7,3)
487 multicall.subtract(7,3)
488 multicall.multiply(7,3)
489 multicall.divide(7,3)
490 result = multicall()
491
492 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493
494
495Convenience Functions
496---------------------
497
498
499.. function:: boolean(value)
500
501 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
502 ``False``.
503
504
505.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
506
507 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
508 is true. *params* can be either a tuple of arguments or an instance of the
509 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
510 can be returned, meaning that *params* must be of length 1. *encoding*, if
511 supplied, is the encoding to use in the generated XML; the default is UTF-8.
512 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
513 it via an extension, provide a true value for *allow_none*.
514
515
516.. function:: loads(data[, use_datetime])
517
518 Convert an XML-RPC request or response into Python objects, a ``(params,
519 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
520 ``None`` if no method name is present in the packet. If the XML-RPC packet
521 represents a fault condition, this function will raise a :exc:`Fault` exception.
522 The *use_datetime* flag can be used to cause date/time values to be presented as
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000523 :class:`datetime.datetime` objects; this is false by default.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000524
525 .. versionchanged:: 2.5
526 The *use_datetime* flag was added.
527
528
529.. _xmlrpc-client-example:
530
531Example of Client Usage
532-----------------------
533
534::
535
536 # simple test program (from the XML-RPC specification)
537 from xmlrpclib import ServerProxy, Error
538
539 # server = ServerProxy("http://localhost:8000") # local server
540 server = ServerProxy("http://betty.userland.com")
541
542 print server
543
544 try:
545 print server.examples.getStateName(41)
546 except Error, v:
547 print "ERROR", v
548
549To access an XML-RPC server through a proxy, you need to define a custom
Georg Brandlb19be572007-12-29 10:57:00 +0000550transport. The following example shows how:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000551
Georg Brandlb19be572007-12-29 10:57:00 +0000552.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl8ec7f652007-08-15 14:28:01 +0000553
554::
555
556 import xmlrpclib, httplib
557
558 class ProxiedTransport(xmlrpclib.Transport):
559 def set_proxy(self, proxy):
560 self.proxy = proxy
561 def make_connection(self, host):
562 self.realhost = host
563 h = httplib.HTTP(self.proxy)
564 return h
565 def send_request(self, connection, handler, request_body):
566 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
567 def send_host(self, connection, host):
568 connection.putheader('Host', self.realhost)
569
570 p = ProxiedTransport()
571 p.set_proxy('proxy-server:8080')
572 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
573 print server.currentTime.getCurrentTime()
574
Georg Brandl0a0cf162007-12-03 20:03:46 +0000575
576Example of Client and Server Usage
577----------------------------------
578
579See :ref:`simplexmlrpcserver-example`.
580
581