blob: c1f13c389c86a1551aecdcde196cd2d5947db360 [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
Georg Brandle6bcc912008-05-12 18:05:20 +000089 :exc:`Error`. Note that the xmlrpclib module currently does not marshal
90 instances of subclasses of builtin types.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
93 will be automatically escaped. However, it's the caller's responsibility to
94 ensure that the string is free of characters that aren't allowed in XML, such as
95 the control characters with ASCII values between 0 and 31 (except, of course,
96 tab, newline and carriage return); failing to do this will result in an XML-RPC
97 request that isn't well-formed XML. If you have to pass arbitrary strings via
98 XML-RPC, use the :class:`Binary` wrapper class described below.
99
100 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
101 compatibility. New code should use :class:`ServerProxy`.
102
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104.. seealso::
105
106 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000107 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000108 Contains pretty much everything an XML-RPC client developer needs to know.
109
Christian Heimesa62da1d2008-01-12 19:39:10 +0000110 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
111 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000113 `XML-RPC Specification <http://www.xmlrpc.com/spec>`_
114 The official specification.
115
116 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
117 Fredrik Lundh's "unofficial errata, intended to clarify certain
118 details in the XML-RPC specification, as well as hint at
119 'best practices' to use when designing your own XML-RPC
120 implementations."
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122.. _serverproxy-objects:
123
124ServerProxy Objects
125-------------------
126
127A :class:`ServerProxy` instance has a method corresponding to each remote
128procedure call accepted by the XML-RPC server. Calling the method performs an
129RPC, dispatched by both name and argument signature (e.g. the same method name
130can be overloaded with multiple argument signatures). The RPC finishes by
131returning a value, which may be either returned data in a conformant type or a
132:class:`Fault` or :class:`ProtocolError` object indicating an error.
133
134Servers that support the XML introspection API support some common methods
135grouped under the reserved :attr:`system` member:
136
137
138.. method:: ServerProxy.system.listMethods()
139
140 This method returns a list of strings, one for each (non-system) method
141 supported by the XML-RPC server.
142
143
144.. method:: ServerProxy.system.methodSignature(name)
145
146 This method takes one parameter, the name of a method implemented by the XML-RPC
147 server.It returns an array of possible signatures for this method. A signature
148 is an array of types. The first of these types is the return type of the method,
149 the rest are parameters.
150
151 Because multiple signatures (ie. overloading) is permitted, this method returns
152 a list of signatures rather than a singleton.
153
154 Signatures themselves are restricted to the top level parameters expected by a
155 method. For instance if a method expects one array of structs as a parameter,
156 and it returns a string, its signature is simply "string, array". If it expects
157 three integers and returns a string, its signature is "string, int, int, int".
158
159 If no signature is defined for the method, a non-array value is returned. In
160 Python this means that the type of the returned value will be something other
161 that list.
162
163
164.. method:: ServerProxy.system.methodHelp(name)
165
166 This method takes one parameter, the name of a method implemented by the XML-RPC
167 server. It returns a documentation string describing the use of that method. If
168 no such string is available, an empty string is returned. The documentation
169 string may contain HTML markup.
170
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172.. _boolean-objects:
173
174Boolean Objects
175---------------
176
177This class may be initialized from any Python value; the instance returned
178depends only on its truth value. It supports various Python operators through
179:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__bool__`
180methods, all implemented in the obvious ways.
181
182It also has the following method, supported mainly for internal use by the
183unmarshalling code:
184
185
186.. method:: Boolean.encode(out)
187
188 Write the XML-RPC encoding of this Boolean item to the out stream object.
189
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000190A working example follows. The server code::
191
192 import xmlrpclib
193 from SimpleXMLRPCServer import SimpleXMLRPCServer
194
195 def is_even(n):
196 return n%2 == 0
197
198 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000199 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000200 server.register_function(is_even, "is_even")
201 server.serve_forever()
202
203The client code for the preceding server::
204
205 import xmlrpclib
206
207 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
Georg Brandlf6945182008-02-01 11:56:49 +0000208 print("3 is even: %s" % str(proxy.is_even(3)))
209 print("100 is even: %s" % str(proxy.is_even(100)))
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211.. _datetime-objects:
212
213DateTime Objects
214----------------
215
Christian Heimes05e8be12008-02-23 18:30:17 +0000216This class may be initialized with seconds since the epoch, a time
217tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
218instance. It has the following methods, supported mainly for internal
219use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221
222.. method:: DateTime.decode(string)
223
224 Accept a string as the instance's new time value.
225
226
227.. method:: DateTime.encode(out)
228
229 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
230 object.
231
232It also supports certain of Python's built-in operators through :meth:`__cmp__`
233and :meth:`__repr__` methods.
234
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000235A working example follows. The server code::
236
237 import datetime
238 from SimpleXMLRPCServer import SimpleXMLRPCServer
239 import xmlrpclib
240
241 def today():
242 today = datetime.datetime.today()
243 return xmlrpclib.DateTime(today)
244
245 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000246 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000247 server.register_function(today, "today")
248 server.serve_forever()
249
250The client code for the preceding server::
251
252 import xmlrpclib
253 import datetime
254
255 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
256
257 today = proxy.today()
258 # convert the ISO8601 string to a datetime object
259 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
Georg Brandlf6945182008-02-01 11:56:49 +0000260 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262.. _binary-objects:
263
264Binary Objects
265--------------
266
267This class may be initialized from string data (which may include NULs). The
268primary access to the content of a :class:`Binary` object is provided by an
269attribute:
270
271
272.. attribute:: Binary.data
273
274 The binary data encapsulated by the :class:`Binary` instance. The data is
275 provided as an 8-bit string.
276
277:class:`Binary` objects have the following methods, supported mainly for
278internal use by the marshalling/unmarshalling code:
279
280
281.. method:: Binary.decode(string)
282
283 Accept a base64 string and decode it as the instance's new data.
284
285
286.. method:: Binary.encode(out)
287
288 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
289
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000290 The encoded data will have newlines every 76 characters as per
291 `RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
292 which was the de facto standard base64 specification when the
293 XML-RPC spec was written.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295It also supports certain of Python's built-in operators through a
296:meth:`__cmp__` method.
297
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000298Example usage of the binary objects. We're going to transfer an image over
299XMLRPC::
300
301 from SimpleXMLRPCServer import SimpleXMLRPCServer
302 import xmlrpclib
303
304 def python_logo():
305 handle = open("python_logo.jpg")
306 return xmlrpclib.Binary(handle.read())
307 handle.close()
308
309 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000310 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000311 server.register_function(python_logo, 'python_logo')
312
313 server.serve_forever()
314
315The client gets the image and saves it to a file::
316
317 import xmlrpclib
318
319 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
320 handle = open("fetched_python_logo.jpg", "w")
321 handle.write(proxy.python_logo().data)
322 handle.close()
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324.. _fault-objects:
325
326Fault Objects
327-------------
328
329A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
330objects have the following members:
331
332
333.. attribute:: Fault.faultCode
334
335 A string indicating the fault type.
336
337
338.. attribute:: Fault.faultString
339
340 A string containing a diagnostic message associated with the fault.
341
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000342In the following example we're going to intentionally cause a :exc:`Fault` by
343returning a complex type object. The server code::
344
345 from SimpleXMLRPCServer import SimpleXMLRPCServer
346
347 # A marshalling error is going to occur because we're returning a
348 # complex number
349 def add(x,y):
350 return x+y+0j
351
352 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000353 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000354 server.register_function(add, 'add')
355
356 server.serve_forever()
357
358The client code for the preceding server::
359
360 import xmlrpclib
361
362 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
363 try:
364 proxy.add(2, 5)
365 except xmlrpclib.Fault, err:
Georg Brandlf6945182008-02-01 11:56:49 +0000366 print("A fault occured")
367 print("Fault code: %d" % err.faultCode)
368 print("Fault string: %s" % err.faultString)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000369
370
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372.. _protocol-error-objects:
373
374ProtocolError Objects
375---------------------
376
377A :class:`ProtocolError` object describes a protocol error in the underlying
378transport layer (such as a 404 'not found' error if the server named by the URI
379does not exist). It has the following members:
380
381
382.. attribute:: ProtocolError.url
383
384 The URI or URL that triggered the error.
385
386
387.. attribute:: ProtocolError.errcode
388
389 The error code.
390
391
392.. attribute:: ProtocolError.errmsg
393
394 The error message or diagnostic string.
395
396
397.. attribute:: ProtocolError.headers
398
Guido van Rossum460add42007-08-23 02:13:35 +0000399 A dict containing the headers of the HTTP/HTTPS request that triggered the
Georg Brandl116aa622007-08-15 14:28:22 +0000400 error.
401
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000402In the following example we're going to intentionally cause a :exc:`ProtocolError`
403by providing an invalid URI::
404
405 import xmlrpclib
406
407 # create a ServerProxy with an invalid URI
408 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
409
410 try:
411 proxy.some_method()
412 except xmlrpclib.ProtocolError, err:
Georg Brandlf6945182008-02-01 11:56:49 +0000413 print("A protocol error occured")
414 print("URL: %s" % err.url)
415 print("HTTP/HTTPS headers: %s" % err.headers)
416 print("Error code: %d" % err.errcode)
417 print("Error message: %s" % err.errmsg)
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419MultiCall Objects
420-----------------
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
423encapsulate multiple calls to a remote server into a single request.
424
425
426.. class:: MultiCall(server)
427
428 Create an object used to boxcar method calls. *server* is the eventual target of
429 the call. Calls can be made to the result object, but they will immediately
430 return ``None``, and only store the call name and parameters in the
431 :class:`MultiCall` object. Calling the object itself causes all stored calls to
432 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000433 is a :term:`generator`; iterating over this generator yields the individual
434 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000436A usage example of this class follows. The server code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000438 from SimpleXMLRPCServer import SimpleXMLRPCServer
439
440 def add(x,y):
441 return x+y
442
443 def subtract(x, y):
444 return x-y
445
446 def multiply(x, y):
447 return x*y
448
449 def divide(x, y):
450 return x/y
451
452 # A simple server with simple arithmetic functions
453 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000454 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000455 server.register_multicall_functions()
456 server.register_function(add, 'add')
457 server.register_function(subtract, 'subtract')
458 server.register_function(multiply, 'multiply')
459 server.register_function(divide, 'divide')
460 server.serve_forever()
461
462The client code for the preceding server::
463
464 import xmlrpclib
465
466 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
467 multicall = xmlrpclib.MultiCall(proxy)
468 multicall.add(7,3)
469 multicall.subtract(7,3)
470 multicall.multiply(7,3)
471 multicall.divide(7,3)
472 result = multicall()
473
Georg Brandlf6945182008-02-01 11:56:49 +0000474 print("7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result))
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476
477Convenience Functions
478---------------------
479
480
481.. function:: boolean(value)
482
483 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
484 ``False``.
485
486
487.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
488
489 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
490 is true. *params* can be either a tuple of arguments or an instance of the
491 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
492 can be returned, meaning that *params* must be of length 1. *encoding*, if
493 supplied, is the encoding to use in the generated XML; the default is UTF-8.
494 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
495 it via an extension, provide a true value for *allow_none*.
496
497
498.. function:: loads(data[, use_datetime])
499
500 Convert an XML-RPC request or response into Python objects, a ``(params,
501 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
502 ``None`` if no method name is present in the packet. If the XML-RPC packet
503 represents a fault condition, this function will raise a :exc:`Fault` exception.
504 The *use_datetime* flag can be used to cause date/time values to be presented as
Christian Heimes05e8be12008-02-23 18:30:17 +0000505 :class:`datetime.datetime` objects; this is false by default.
Georg Brandl116aa622007-08-15 14:28:22 +0000506
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508.. _xmlrpc-client-example:
509
510Example of Client Usage
511-----------------------
512
513::
514
515 # simple test program (from the XML-RPC specification)
516 from xmlrpclib import ServerProxy, Error
517
518 # server = ServerProxy("http://localhost:8000") # local server
519 server = ServerProxy("http://betty.userland.com")
520
Collin Winterc79461b2007-09-01 23:34:30 +0000521 print(server)
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523 try:
Collin Winterc79461b2007-09-01 23:34:30 +0000524 print(server.examples.getStateName(41))
Georg Brandl116aa622007-08-15 14:28:22 +0000525 except Error as v:
Collin Winterc79461b2007-09-01 23:34:30 +0000526 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528To access an XML-RPC server through a proxy, you need to define a custom
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000529transport. The following example shows how:
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000531.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533::
534
535 import xmlrpclib, httplib
536
537 class ProxiedTransport(xmlrpclib.Transport):
538 def set_proxy(self, proxy):
539 self.proxy = proxy
540 def make_connection(self, host):
541 self.realhost = host
542 h = httplib.HTTP(self.proxy)
543 return h
544 def send_request(self, connection, handler, request_body):
545 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
546 def send_host(self, connection, host):
547 connection.putheader('Host', self.realhost)
548
549 p = ProxiedTransport()
550 p.set_proxy('proxy-server:8080')
551 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
Collin Winterc79461b2007-09-01 23:34:30 +0000552 print(server.currentTime.getCurrentTime())
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000554
555Example of Client and Server Usage
556----------------------------------
557
558See :ref:`simplexmlrpcserver-example`.
559
560