blob: 3f0bf3b5932f03d6015074aa2e1e38eb53d244f1 [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.
Christian Heimes05e8be12008-02-23 18:30:17 +000035 :class:`datetime.datetime` objects may be passed to calls.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
38 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
39 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
40 the remote server as part of the connection process when invoking an XML-RPC
41 method. You only need to use this if the remote server requires a Basic
42 Authentication user and password.
43
44 The returned instance is a proxy object with methods that can be used to invoke
45 corresponding RPC calls on the remote server. If the remote server supports the
46 introspection API, the proxy can also be used to query the remote server for the
47 methods it supports (service discovery) and fetch other server-associated
48 metadata.
49
50 :class:`ServerProxy` instance methods take Python basic types and objects as
51 arguments and return Python basic types and classes. Types that are conformable
52 (e.g. that can be marshalled through XML), include the following (and except
53 where noted, they are unmarshalled as the same Python type):
54
55 +---------------------------------+---------------------------------------------+
56 | Name | Meaning |
57 +=================================+=============================================+
58 | :const:`boolean` | The :const:`True` and :const:`False` |
59 | | constants |
60 +---------------------------------+---------------------------------------------+
61 | :const:`integers` | Pass in directly |
62 +---------------------------------+---------------------------------------------+
63 | :const:`floating-point numbers` | Pass in directly |
64 +---------------------------------+---------------------------------------------+
65 | :const:`strings` | Pass in directly |
66 +---------------------------------+---------------------------------------------+
67 | :const:`arrays` | Any Python sequence type containing |
68 | | conformable elements. Arrays are returned |
69 | | as lists |
70 +---------------------------------+---------------------------------------------+
71 | :const:`structures` | A Python dictionary. Keys must be strings, |
72 | | values may be any conformable type. Objects |
73 | | of user-defined classes can be passed in; |
74 | | only their *__dict__* attribute is |
75 | | transmitted. |
76 +---------------------------------+---------------------------------------------+
77 | :const:`dates` | in seconds since the epoch (pass in an |
78 | | instance of the :class:`DateTime` class) or |
Christian Heimes05e8be12008-02-23 18:30:17 +000079 | | a :class:`datetime.datetime` instance. |
Georg Brandl116aa622007-08-15 14:28:22 +000080 +---------------------------------+---------------------------------------------+
81 | :const:`binary data` | pass in an instance of the :class:`Binary` |
82 | | wrapper class |
83 +---------------------------------+---------------------------------------------+
84
85 This is the full set of data types supported by XML-RPC. Method calls may also
86 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
87 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
88 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
89 :exc:`Error`. Note that even though starting with Python 2.2 you can subclass
90 builtin types, the xmlrpclib module currently does not marshal instances of such
91 subclasses.
92
93 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
94 will be automatically escaped. However, it's the caller's responsibility to
95 ensure that the string is free of characters that aren't allowed in XML, such as
96 the control characters with ASCII values between 0 and 31 (except, of course,
97 tab, newline and carriage return); failing to do this will result in an XML-RPC
98 request that isn't well-formed XML. If you have to pass arbitrary strings via
99 XML-RPC, use the :class:`Binary` wrapper class described below.
100
101 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
102 compatibility. New code should use :class:`ServerProxy`.
103
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105.. seealso::
106
107 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000108 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000109 Contains pretty much everything an XML-RPC client developer needs to know.
110
Christian Heimesa62da1d2008-01-12 19:39:10 +0000111 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
112 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114
115.. _serverproxy-objects:
116
117ServerProxy Objects
118-------------------
119
120A :class:`ServerProxy` instance has a method corresponding to each remote
121procedure call accepted by the XML-RPC server. Calling the method performs an
122RPC, dispatched by both name and argument signature (e.g. the same method name
123can be overloaded with multiple argument signatures). The RPC finishes by
124returning a value, which may be either returned data in a conformant type or a
125:class:`Fault` or :class:`ProtocolError` object indicating an error.
126
127Servers that support the XML introspection API support some common methods
128grouped under the reserved :attr:`system` member:
129
130
131.. method:: ServerProxy.system.listMethods()
132
133 This method returns a list of strings, one for each (non-system) method
134 supported by the XML-RPC server.
135
136
137.. method:: ServerProxy.system.methodSignature(name)
138
139 This method takes one parameter, the name of a method implemented by the XML-RPC
140 server.It returns an array of possible signatures for this method. A signature
141 is an array of types. The first of these types is the return type of the method,
142 the rest are parameters.
143
144 Because multiple signatures (ie. overloading) is permitted, this method returns
145 a list of signatures rather than a singleton.
146
147 Signatures themselves are restricted to the top level parameters expected by a
148 method. For instance if a method expects one array of structs as a parameter,
149 and it returns a string, its signature is simply "string, array". If it expects
150 three integers and returns a string, its signature is "string, int, int, int".
151
152 If no signature is defined for the method, a non-array value is returned. In
153 Python this means that the type of the returned value will be something other
154 that list.
155
156
157.. method:: ServerProxy.system.methodHelp(name)
158
159 This method takes one parameter, the name of a method implemented by the XML-RPC
160 server. It returns a documentation string describing the use of that method. If
161 no such string is available, an empty string is returned. The documentation
162 string may contain HTML markup.
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. _boolean-objects:
166
167Boolean Objects
168---------------
169
170This class may be initialized from any Python value; the instance returned
171depends only on its truth value. It supports various Python operators through
172:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__bool__`
173methods, all implemented in the obvious ways.
174
175It also has the following method, supported mainly for internal use by the
176unmarshalling code:
177
178
179.. method:: Boolean.encode(out)
180
181 Write the XML-RPC encoding of this Boolean item to the out stream object.
182
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000183A working example follows. The server code::
184
185 import xmlrpclib
186 from SimpleXMLRPCServer import SimpleXMLRPCServer
187
188 def is_even(n):
189 return n%2 == 0
190
191 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000192 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000193 server.register_function(is_even, "is_even")
194 server.serve_forever()
195
196The client code for the preceding server::
197
198 import xmlrpclib
199
200 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
Georg Brandlf6945182008-02-01 11:56:49 +0000201 print("3 is even: %s" % str(proxy.is_even(3)))
202 print("100 is even: %s" % str(proxy.is_even(100)))
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204.. _datetime-objects:
205
206DateTime Objects
207----------------
208
Christian Heimes05e8be12008-02-23 18:30:17 +0000209This class may be initialized with seconds since the epoch, a time
210tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
211instance. It has the following methods, supported mainly for internal
212use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. method:: DateTime.decode(string)
216
217 Accept a string as the instance's new time value.
218
219
220.. method:: DateTime.encode(out)
221
222 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
223 object.
224
225It also supports certain of Python's built-in operators through :meth:`__cmp__`
226and :meth:`__repr__` methods.
227
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000228A working example follows. The server code::
229
230 import datetime
231 from SimpleXMLRPCServer import SimpleXMLRPCServer
232 import xmlrpclib
233
234 def today():
235 today = datetime.datetime.today()
236 return xmlrpclib.DateTime(today)
237
238 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000239 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000240 server.register_function(today, "today")
241 server.serve_forever()
242
243The client code for the preceding server::
244
245 import xmlrpclib
246 import datetime
247
248 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
249
250 today = proxy.today()
251 # convert the ISO8601 string to a datetime object
252 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
Georg Brandlf6945182008-02-01 11:56:49 +0000253 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255.. _binary-objects:
256
257Binary Objects
258--------------
259
260This class may be initialized from string data (which may include NULs). The
261primary access to the content of a :class:`Binary` object is provided by an
262attribute:
263
264
265.. attribute:: Binary.data
266
267 The binary data encapsulated by the :class:`Binary` instance. The data is
268 provided as an 8-bit string.
269
270:class:`Binary` objects have the following methods, supported mainly for
271internal use by the marshalling/unmarshalling code:
272
273
274.. method:: Binary.decode(string)
275
276 Accept a base64 string and decode it as the instance's new data.
277
278
279.. method:: Binary.encode(out)
280
281 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
282
283It also supports certain of Python's built-in operators through a
284:meth:`__cmp__` method.
285
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000286Example usage of the binary objects. We're going to transfer an image over
287XMLRPC::
288
289 from SimpleXMLRPCServer import SimpleXMLRPCServer
290 import xmlrpclib
291
292 def python_logo():
293 handle = open("python_logo.jpg")
294 return xmlrpclib.Binary(handle.read())
295 handle.close()
296
297 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000298 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000299 server.register_function(python_logo, 'python_logo')
300
301 server.serve_forever()
302
303The client gets the image and saves it to a file::
304
305 import xmlrpclib
306
307 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
308 handle = open("fetched_python_logo.jpg", "w")
309 handle.write(proxy.python_logo().data)
310 handle.close()
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312.. _fault-objects:
313
314Fault Objects
315-------------
316
317A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
318objects have the following members:
319
320
321.. attribute:: Fault.faultCode
322
323 A string indicating the fault type.
324
325
326.. attribute:: Fault.faultString
327
328 A string containing a diagnostic message associated with the fault.
329
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000330In the following example we're going to intentionally cause a :exc:`Fault` by
331returning a complex type object. The server code::
332
333 from SimpleXMLRPCServer import SimpleXMLRPCServer
334
335 # A marshalling error is going to occur because we're returning a
336 # complex number
337 def add(x,y):
338 return x+y+0j
339
340 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000341 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000342 server.register_function(add, 'add')
343
344 server.serve_forever()
345
346The client code for the preceding server::
347
348 import xmlrpclib
349
350 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
351 try:
352 proxy.add(2, 5)
353 except xmlrpclib.Fault, err:
Georg Brandlf6945182008-02-01 11:56:49 +0000354 print("A fault occured")
355 print("Fault code: %d" % err.faultCode)
356 print("Fault string: %s" % err.faultString)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000357
358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360.. _protocol-error-objects:
361
362ProtocolError Objects
363---------------------
364
365A :class:`ProtocolError` object describes a protocol error in the underlying
366transport layer (such as a 404 'not found' error if the server named by the URI
367does not exist). It has the following members:
368
369
370.. attribute:: ProtocolError.url
371
372 The URI or URL that triggered the error.
373
374
375.. attribute:: ProtocolError.errcode
376
377 The error code.
378
379
380.. attribute:: ProtocolError.errmsg
381
382 The error message or diagnostic string.
383
384
385.. attribute:: ProtocolError.headers
386
Guido van Rossum460add42007-08-23 02:13:35 +0000387 A dict containing the headers of the HTTP/HTTPS request that triggered the
Georg Brandl116aa622007-08-15 14:28:22 +0000388 error.
389
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000390In the following example we're going to intentionally cause a :exc:`ProtocolError`
391by providing an invalid URI::
392
393 import xmlrpclib
394
395 # create a ServerProxy with an invalid URI
396 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
397
398 try:
399 proxy.some_method()
400 except xmlrpclib.ProtocolError, err:
Georg Brandlf6945182008-02-01 11:56:49 +0000401 print("A protocol error occured")
402 print("URL: %s" % err.url)
403 print("HTTP/HTTPS headers: %s" % err.headers)
404 print("Error code: %d" % err.errcode)
405 print("Error message: %s" % err.errmsg)
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407MultiCall Objects
408-----------------
409
Georg Brandl116aa622007-08-15 14:28:22 +0000410In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
411encapsulate multiple calls to a remote server into a single request.
412
413
414.. class:: MultiCall(server)
415
416 Create an object used to boxcar method calls. *server* is the eventual target of
417 the call. Calls can be made to the result object, but they will immediately
418 return ``None``, and only store the call name and parameters in the
419 :class:`MultiCall` object. Calling the object itself causes all stored calls to
420 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000421 is a :term:`generator`; iterating over this generator yields the individual
422 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000424A usage example of this class follows. The server code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000426 from SimpleXMLRPCServer import SimpleXMLRPCServer
427
428 def add(x,y):
429 return x+y
430
431 def subtract(x, y):
432 return x-y
433
434 def multiply(x, y):
435 return x*y
436
437 def divide(x, y):
438 return x/y
439
440 # A simple server with simple arithmetic functions
441 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000442 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000443 server.register_multicall_functions()
444 server.register_function(add, 'add')
445 server.register_function(subtract, 'subtract')
446 server.register_function(multiply, 'multiply')
447 server.register_function(divide, 'divide')
448 server.serve_forever()
449
450The client code for the preceding server::
451
452 import xmlrpclib
453
454 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
455 multicall = xmlrpclib.MultiCall(proxy)
456 multicall.add(7,3)
457 multicall.subtract(7,3)
458 multicall.multiply(7,3)
459 multicall.divide(7,3)
460 result = multicall()
461
Georg Brandlf6945182008-02-01 11:56:49 +0000462 print("7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result))
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464
465Convenience Functions
466---------------------
467
468
469.. function:: boolean(value)
470
471 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
472 ``False``.
473
474
475.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
476
477 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
478 is true. *params* can be either a tuple of arguments or an instance of the
479 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
480 can be returned, meaning that *params* must be of length 1. *encoding*, if
481 supplied, is the encoding to use in the generated XML; the default is UTF-8.
482 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
483 it via an extension, provide a true value for *allow_none*.
484
485
486.. function:: loads(data[, use_datetime])
487
488 Convert an XML-RPC request or response into Python objects, a ``(params,
489 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
490 ``None`` if no method name is present in the packet. If the XML-RPC packet
491 represents a fault condition, this function will raise a :exc:`Fault` exception.
492 The *use_datetime* flag can be used to cause date/time values to be presented as
Christian Heimes05e8be12008-02-23 18:30:17 +0000493 :class:`datetime.datetime` objects; this is false by default.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. _xmlrpc-client-example:
497
498Example of Client Usage
499-----------------------
500
501::
502
503 # simple test program (from the XML-RPC specification)
504 from xmlrpclib import ServerProxy, Error
505
506 # server = ServerProxy("http://localhost:8000") # local server
507 server = ServerProxy("http://betty.userland.com")
508
Collin Winterc79461b2007-09-01 23:34:30 +0000509 print(server)
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 try:
Collin Winterc79461b2007-09-01 23:34:30 +0000512 print(server.examples.getStateName(41))
Georg Brandl116aa622007-08-15 14:28:22 +0000513 except Error as v:
Collin Winterc79461b2007-09-01 23:34:30 +0000514 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516To access an XML-RPC server through a proxy, you need to define a custom
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000517transport. The following example shows how:
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000519.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521::
522
523 import xmlrpclib, httplib
524
525 class ProxiedTransport(xmlrpclib.Transport):
526 def set_proxy(self, proxy):
527 self.proxy = proxy
528 def make_connection(self, host):
529 self.realhost = host
530 h = httplib.HTTP(self.proxy)
531 return h
532 def send_request(self, connection, handler, request_body):
533 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
534 def send_host(self, connection, host):
535 connection.putheader('Host', self.realhost)
536
537 p = ProxiedTransport()
538 p.set_proxy('proxy-server:8080')
539 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
Collin Winterc79461b2007-09-01 23:34:30 +0000540 print(server.currentTime.getCurrentTime())
Georg Brandl116aa622007-08-15 14:28:22 +0000541
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000542
543Example of Client and Server Usage
544----------------------------------
545
546See :ref:`simplexmlrpcserver-example`.
547
548