blob: 1c50b799ab853b631f377d08afc988c906aeb686 [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
9
Georg Brandlb19be572007-12-29 10:57:00 +000010.. XXX Not everything is documented yet. It might be good to describe
11 Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
Georg Brandl8ec7f652007-08-15 14:28:01 +000012
13.. versionadded:: 2.2
14
15XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
16transport. With it, a client can call methods with parameters on a remote
17server (the server is named by a URI) and get back structured data. This module
18supports writing XML-RPC client code; it handles all the details of translating
19between conformable Python objects and XML on the wire.
20
21
22.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]])
23
24 A :class:`ServerProxy` instance is an object that manages communication with a
25 remote XML-RPC server. The required first argument is a URI (Uniform Resource
26 Indicator), and will normally be the URL of the server. The optional second
27 argument is a transport factory instance; by default it is an internal
28 :class:`SafeTransport` instance for https: URLs and an internal HTTP
29 :class:`Transport` instance otherwise. The optional third argument is an
30 encoding, by default UTF-8. The optional fourth argument is a debugging flag.
31 If *allow_none* is true, the Python constant ``None`` will be translated into
32 XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
33 a commonly-used extension to the XML-RPC specification, but isn't supported by
34 all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
35 description. The *use_datetime* flag can be used to cause date/time values to
36 be presented as :class:`datetime.datetime` objects; this is false by default.
37 :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time`
38 objects may be passed to calls. :class:`datetime.date` objects are converted
39 with a time of "00:00:00". :class:`datetime.time` objects are converted using
40 today's date.
41
42 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
43 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
44 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
45 the remote server as part of the connection process when invoking an XML-RPC
46 method. You only need to use this if the remote server requires a Basic
47 Authentication user and password.
48
49 The returned instance is a proxy object with methods that can be used to invoke
50 corresponding RPC calls on the remote server. If the remote server supports the
51 introspection API, the proxy can also be used to query the remote server for the
52 methods it supports (service discovery) and fetch other server-associated
53 metadata.
54
55 :class:`ServerProxy` instance methods take Python basic types and objects as
56 arguments and return Python basic types and classes. Types that are conformable
57 (e.g. that can be marshalled through XML), include the following (and except
58 where noted, they are unmarshalled as the same Python type):
59
60 +---------------------------------+---------------------------------------------+
61 | Name | Meaning |
62 +=================================+=============================================+
63 | :const:`boolean` | The :const:`True` and :const:`False` |
64 | | constants |
65 +---------------------------------+---------------------------------------------+
66 | :const:`integers` | Pass in directly |
67 +---------------------------------+---------------------------------------------+
68 | :const:`floating-point numbers` | Pass in directly |
69 +---------------------------------+---------------------------------------------+
70 | :const:`strings` | Pass in directly |
71 +---------------------------------+---------------------------------------------+
72 | :const:`arrays` | Any Python sequence type containing |
73 | | conformable elements. Arrays are returned |
74 | | as lists |
75 +---------------------------------+---------------------------------------------+
76 | :const:`structures` | A Python dictionary. Keys must be strings, |
77 | | values may be any conformable type. Objects |
78 | | of user-defined classes can be passed in; |
79 | | only their *__dict__* attribute is |
80 | | transmitted. |
81 +---------------------------------+---------------------------------------------+
82 | :const:`dates` | in seconds since the epoch (pass in an |
83 | | instance of the :class:`DateTime` class) or |
84 | | a :class:`datetime.datetime`, |
85 | | :class:`datetime.date` or |
86 | | :class:`datetime.time` instance |
87 +---------------------------------+---------------------------------------------+
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
129
130.. _serverproxy-objects:
131
132ServerProxy Objects
133-------------------
134
135A :class:`ServerProxy` instance has a method corresponding to each remote
136procedure call accepted by the XML-RPC server. Calling the method performs an
137RPC, dispatched by both name and argument signature (e.g. the same method name
138can be overloaded with multiple argument signatures). The RPC finishes by
139returning a value, which may be either returned data in a conformant type or a
140:class:`Fault` or :class:`ProtocolError` object indicating an error.
141
142Servers that support the XML introspection API support some common methods
143grouped under the reserved :attr:`system` member:
144
145
146.. method:: ServerProxy.system.listMethods()
147
148 This method returns a list of strings, one for each (non-system) method
149 supported by the XML-RPC server.
150
151
152.. method:: ServerProxy.system.methodSignature(name)
153
154 This method takes one parameter, the name of a method implemented by the XML-RPC
155 server.It returns an array of possible signatures for this method. A signature
156 is an array of types. The first of these types is the return type of the method,
157 the rest are parameters.
158
159 Because multiple signatures (ie. overloading) is permitted, this method returns
160 a list of signatures rather than a singleton.
161
162 Signatures themselves are restricted to the top level parameters expected by a
163 method. For instance if a method expects one array of structs as a parameter,
164 and it returns a string, its signature is simply "string, array". If it expects
165 three integers and returns a string, its signature is "string, int, int, int".
166
167 If no signature is defined for the method, a non-array value is returned. In
168 Python this means that the type of the returned value will be something other
169 that list.
170
171
172.. method:: ServerProxy.system.methodHelp(name)
173
174 This method takes one parameter, the name of a method implemented by the XML-RPC
175 server. It returns a documentation string describing the use of that method. If
176 no such string is available, an empty string is returned. The documentation
177 string may contain HTML markup.
178
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
180.. _boolean-objects:
181
182Boolean Objects
183---------------
184
185This class may be initialized from any Python value; the instance returned
186depends only on its truth value. It supports various Python operators through
187:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
188methods, all implemented in the obvious ways.
189
190It also has the following method, supported mainly for internal use by the
191unmarshalling code:
192
193
194.. method:: Boolean.encode(out)
195
196 Write the XML-RPC encoding of this Boolean item to the out stream object.
197
Georg Brandl0a0cf162007-12-03 20:03:46 +0000198A working example follows. The server code::
199
200 import xmlrpclib
201 from SimpleXMLRPCServer import SimpleXMLRPCServer
202
203 def is_even(n):
204 return n%2 == 0
205
206 server = SimpleXMLRPCServer(("localhost", 8000))
207 print "Listening on port 8000..."
208 server.register_function(is_even, "is_even")
209 server.serve_forever()
210
211The client code for the preceding server::
212
213 import xmlrpclib
214
215 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
216 print "3 is even: %s" % str(proxy.is_even(3))
217 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218
219.. _datetime-objects:
220
221DateTime Objects
222----------------
223
224This class may be initialized with seconds since the epoch, a time tuple, an ISO
2258601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
226or :class:`datetime.time` instance. It has the following methods, supported
227mainly for internal use by the marshalling/unmarshalling code:
228
229
230.. method:: DateTime.decode(string)
231
232 Accept a string as the instance's new time value.
233
234
235.. method:: DateTime.encode(out)
236
237 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
238 object.
239
240It also supports certain of Python's built-in operators through :meth:`__cmp__`
241and :meth:`__repr__` methods.
242
Georg Brandl0a0cf162007-12-03 20:03:46 +0000243A working example follows. The server code::
244
245 import datetime
246 from SimpleXMLRPCServer import SimpleXMLRPCServer
247 import xmlrpclib
248
249 def today():
250 today = datetime.datetime.today()
251 return xmlrpclib.DateTime(today)
252
253 server = SimpleXMLRPCServer(("localhost", 8000))
254 print "Listening on port 8000..."
255 server.register_function(today, "today")
256 server.serve_forever()
257
258The client code for the preceding server::
259
260 import xmlrpclib
261 import datetime
262
263 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
264
265 today = proxy.today()
266 # convert the ISO8601 string to a datetime object
267 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
268 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000269
270.. _binary-objects:
271
272Binary Objects
273--------------
274
275This class may be initialized from string data (which may include NULs). The
276primary access to the content of a :class:`Binary` object is provided by an
277attribute:
278
279
280.. attribute:: Binary.data
281
282 The binary data encapsulated by the :class:`Binary` instance. The data is
283 provided as an 8-bit string.
284
285:class:`Binary` objects have the following methods, supported mainly for
286internal use by the marshalling/unmarshalling code:
287
288
289.. method:: Binary.decode(string)
290
291 Accept a base64 string and decode it as the instance's new data.
292
293
294.. method:: Binary.encode(out)
295
296 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
297
298It also supports certain of Python's built-in operators through a
299:meth:`__cmp__` method.
300
Georg Brandl0a0cf162007-12-03 20:03:46 +0000301Example usage of the binary objects. We're going to transfer an image over
302XMLRPC::
303
304 from SimpleXMLRPCServer import SimpleXMLRPCServer
305 import xmlrpclib
306
307 def python_logo():
308 handle = open("python_logo.jpg")
309 return xmlrpclib.Binary(handle.read())
310 handle.close()
311
312 server = SimpleXMLRPCServer(("localhost", 8000))
313 print "Listening on port 8000..."
314 server.register_function(python_logo, 'python_logo')
315
316 server.serve_forever()
317
318The client gets the image and saves it to a file::
319
320 import xmlrpclib
321
322 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
323 handle = open("fetched_python_logo.jpg", "w")
324 handle.write(proxy.python_logo().data)
325 handle.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000326
327.. _fault-objects:
328
329Fault Objects
330-------------
331
332A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
333objects have the following members:
334
335
336.. attribute:: Fault.faultCode
337
338 A string indicating the fault type.
339
340
341.. attribute:: Fault.faultString
342
343 A string containing a diagnostic message associated with the fault.
344
Georg Brandl0a0cf162007-12-03 20:03:46 +0000345In the following example we're going to intentionally cause a :exc:`Fault` by
346returning a complex type object. The server code::
347
348 from SimpleXMLRPCServer import SimpleXMLRPCServer
349
350 # A marshalling error is going to occur because we're returning a
351 # complex number
352 def add(x,y):
353 return x+y+0j
354
355 server = SimpleXMLRPCServer(("localhost", 8000))
356 print "Listening on port 8000..."
357 server.register_function(add, 'add')
358
359 server.serve_forever()
360
361The client code for the preceding server::
362
363 import xmlrpclib
364
365 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
366 try:
367 proxy.add(2, 5)
368 except xmlrpclib.Fault, err:
369 print "A fault occured"
370 print "Fault code: %d" % err.faultCode
371 print "Fault string: %s" % err.faultString
372
373
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374
375.. _protocol-error-objects:
376
377ProtocolError Objects
378---------------------
379
380A :class:`ProtocolError` object describes a protocol error in the underlying
381transport layer (such as a 404 'not found' error if the server named by the URI
382does not exist). It has the following members:
383
384
385.. attribute:: ProtocolError.url
386
387 The URI or URL that triggered the error.
388
389
390.. attribute:: ProtocolError.errcode
391
392 The error code.
393
394
395.. attribute:: ProtocolError.errmsg
396
397 The error message or diagnostic string.
398
399
400.. attribute:: ProtocolError.headers
401
402 A string containing the headers of the HTTP/HTTPS request that triggered the
403 error.
404
Georg Brandl0a0cf162007-12-03 20:03:46 +0000405In the following example we're going to intentionally cause a :exc:`ProtocolError`
406by providing an invalid URI::
407
408 import xmlrpclib
409
410 # create a ServerProxy with an invalid URI
411 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
412
413 try:
414 proxy.some_method()
415 except xmlrpclib.ProtocolError, err:
416 print "A protocol error occured"
417 print "URL: %s" % err.url
418 print "HTTP/HTTPS headers: %s" % err.headers
419 print "Error code: %d" % err.errcode
420 print "Error message: %s" % err.errmsg
Georg Brandl8ec7f652007-08-15 14:28:01 +0000421
422MultiCall Objects
423-----------------
424
425.. versionadded:: 2.4
426
427In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
428encapsulate multiple calls to a remote server into a single request.
429
430
431.. class:: MultiCall(server)
432
433 Create an object used to boxcar method calls. *server* is the eventual target of
434 the call. Calls can be made to the result object, but they will immediately
435 return ``None``, and only store the call name and parameters in the
436 :class:`MultiCall` object. Calling the object itself causes all stored calls to
437 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000438 is a :term:`generator`; iterating over this generator yields the individual
439 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440
Georg Brandl0a0cf162007-12-03 20:03:46 +0000441A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000442
Georg Brandl0a0cf162007-12-03 20:03:46 +0000443 from SimpleXMLRPCServer import SimpleXMLRPCServer
444
445 def add(x,y):
446 return x+y
447
448 def subtract(x, y):
449 return x-y
450
451 def multiply(x, y):
452 return x*y
453
454 def divide(x, y):
455 return x/y
456
457 # A simple server with simple arithmetic functions
458 server = SimpleXMLRPCServer(("localhost", 8000))
459 print "Listening on port 8000..."
460 server.register_multicall_functions()
461 server.register_function(add, 'add')
462 server.register_function(subtract, 'subtract')
463 server.register_function(multiply, 'multiply')
464 server.register_function(divide, 'divide')
465 server.serve_forever()
466
467The client code for the preceding server::
468
469 import xmlrpclib
470
471 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
472 multicall = xmlrpclib.MultiCall(proxy)
473 multicall.add(7,3)
474 multicall.subtract(7,3)
475 multicall.multiply(7,3)
476 multicall.divide(7,3)
477 result = multicall()
478
479 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000480
481
482Convenience Functions
483---------------------
484
485
486.. function:: boolean(value)
487
488 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
489 ``False``.
490
491
492.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
493
494 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
495 is true. *params* can be either a tuple of arguments or an instance of the
496 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
497 can be returned, meaning that *params* must be of length 1. *encoding*, if
498 supplied, is the encoding to use in the generated XML; the default is UTF-8.
499 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
500 it via an extension, provide a true value for *allow_none*.
501
502
503.. function:: loads(data[, use_datetime])
504
505 Convert an XML-RPC request or response into Python objects, a ``(params,
506 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
507 ``None`` if no method name is present in the packet. If the XML-RPC packet
508 represents a fault condition, this function will raise a :exc:`Fault` exception.
509 The *use_datetime* flag can be used to cause date/time values to be presented as
510 :class:`datetime.datetime` objects; this is false by default. Note that even if
511 you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
512 objects, they are converted to :class:`DateTime` objects internally, so only
513 :class:`datetime.datetime` objects will be returned.
514
515 .. versionchanged:: 2.5
516 The *use_datetime* flag was added.
517
518
519.. _xmlrpc-client-example:
520
521Example of Client Usage
522-----------------------
523
524::
525
526 # simple test program (from the XML-RPC specification)
527 from xmlrpclib import ServerProxy, Error
528
529 # server = ServerProxy("http://localhost:8000") # local server
530 server = ServerProxy("http://betty.userland.com")
531
532 print server
533
534 try:
535 print server.examples.getStateName(41)
536 except Error, v:
537 print "ERROR", v
538
539To access an XML-RPC server through a proxy, you need to define a custom
Georg Brandlb19be572007-12-29 10:57:00 +0000540transport. The following example shows how:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000541
Georg Brandlb19be572007-12-29 10:57:00 +0000542.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543
544::
545
546 import xmlrpclib, httplib
547
548 class ProxiedTransport(xmlrpclib.Transport):
549 def set_proxy(self, proxy):
550 self.proxy = proxy
551 def make_connection(self, host):
552 self.realhost = host
553 h = httplib.HTTP(self.proxy)
554 return h
555 def send_request(self, connection, handler, request_body):
556 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
557 def send_host(self, connection, host):
558 connection.putheader('Host', self.realhost)
559
560 p = ProxiedTransport()
561 p.set_proxy('proxy-server:8080')
562 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
563 print server.currentTime.getCurrentTime()
564
Georg Brandl0a0cf162007-12-03 20:03:46 +0000565
566Example of Client and Server Usage
567----------------------------------
568
569See :ref:`simplexmlrpcserver-example`.
570
571