Added section on passing contextual information to logging and documentation for...
[python.git] / Doc / library / xmlrpclib.rst
blob1c50b799ab853b631f377d08afc988c906aeb686
1 :mod:`xmlrpclib` --- XML-RPC client access
2 ==========================================
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>
10 .. XXX Not everything is documented yet.  It might be good to describe
11    Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
13 .. versionadded:: 2.2
15 XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
16 transport.  With it, a client can call methods with parameters on a remote
17 server (the server is named by a URI) and get back structured data.  This module
18 supports writing XML-RPC client code; it handles all the details of translating
19 between conformable Python objects and XML on the wire.
22 .. class:: ServerProxy(uri[, transport[, encoding[, verbose[,  allow_none[, use_datetime]]]]])
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.
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.
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.
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):
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    +---------------------------------+---------------------------------------------+
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.
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.
108    :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
109    compatibility.  New code should use :class:`ServerProxy`.
111    .. versionchanged:: 2.5
112       The *use_datetime* flag was added.
114    .. versionchanged:: 2.6
115       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.
120 .. seealso::
122    `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
123       A good description of XML-RPC operation and client software in several languages.
124       Contains pretty much everything an XML-RPC client developer needs to know.
126    `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
127       Describes the XML-RPC protocol extension for introspection.
130 .. _serverproxy-objects:
132 ServerProxy Objects
133 -------------------
135 A :class:`ServerProxy` instance has a method corresponding to each remote
136 procedure call accepted by the XML-RPC server.  Calling the method performs an
137 RPC, dispatched by both name and argument signature (e.g. the same method name
138 can be overloaded with multiple argument signatures).  The RPC finishes by
139 returning a value, which may be either returned data in a conformant type or a
140 :class:`Fault` or :class:`ProtocolError` object indicating an error.
142 Servers that support the XML introspection API support some common methods
143 grouped under the reserved :attr:`system` member:
146 .. method:: ServerProxy.system.listMethods()
148    This method returns a list of strings, one for each (non-system) method
149    supported by the XML-RPC server.
152 .. method:: ServerProxy.system.methodSignature(name)
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.
159    Because multiple signatures (ie. overloading) is permitted, this method returns
160    a list of signatures rather than a singleton.
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".
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.
172 .. method:: ServerProxy.system.methodHelp(name)
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.
180 .. _boolean-objects:
182 Boolean Objects
183 ---------------
185 This class may be initialized from any Python value; the instance returned
186 depends only on its truth value.  It supports various Python operators through
187 :meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
188 methods, all implemented in the obvious ways.
190 It also has the following method, supported mainly for internal use by the
191 unmarshalling code:
194 .. method:: Boolean.encode(out)
196    Write the XML-RPC encoding of this Boolean item to the out stream object.
198 A working example follows. The server code::
200    import xmlrpclib
201    from SimpleXMLRPCServer import SimpleXMLRPCServer
203    def is_even(n):
204        return n%2 == 0
206    server = SimpleXMLRPCServer(("localhost", 8000))
207    print "Listening on port 8000..."
208    server.register_function(is_even, "is_even")
209    server.serve_forever()
211 The client code for the preceding server::
213    import xmlrpclib
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))
219 .. _datetime-objects:
221 DateTime Objects
222 ----------------
224 This class may be initialized with seconds since the epoch, a time tuple, an ISO
225 8601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
226 or :class:`datetime.time` instance.  It has the following methods, supported
227 mainly for internal use by the marshalling/unmarshalling code:
230 .. method:: DateTime.decode(string)
232    Accept a string as the instance's new time value.
235 .. method:: DateTime.encode(out)
237    Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
238    object.
240 It also supports certain of Python's built-in operators through  :meth:`__cmp__`
241 and :meth:`__repr__` methods.
243 A working example follows. The server code::
245    import datetime
246    from SimpleXMLRPCServer import SimpleXMLRPCServer
247    import xmlrpclib
249    def today():
250        today = datetime.datetime.today()
251        return xmlrpclib.DateTime(today)
253    server = SimpleXMLRPCServer(("localhost", 8000))
254    print "Listening on port 8000..."
255    server.register_function(today, "today")
256    server.serve_forever()
258 The client code for the preceding server::
260    import xmlrpclib
261    import datetime
263    proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
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")
270 .. _binary-objects:
272 Binary Objects
273 --------------
275 This class may be initialized from string data (which may include NULs). The
276 primary access to the content of a :class:`Binary` object is provided by an
277 attribute:
280 .. attribute:: Binary.data
282    The binary data encapsulated by the :class:`Binary` instance.  The data is
283    provided as an 8-bit string.
285 :class:`Binary` objects have the following methods, supported mainly for
286 internal use by the marshalling/unmarshalling code:
289 .. method:: Binary.decode(string)
291    Accept a base64 string and decode it as the instance's new data.
294 .. method:: Binary.encode(out)
296    Write the XML-RPC base 64 encoding of this binary item to the out stream object.
298 It also supports certain of Python's built-in operators through a
299 :meth:`__cmp__` method.
301 Example usage of the binary objects.  We're going to transfer an image over
302 XMLRPC::
304    from SimpleXMLRPCServer import SimpleXMLRPCServer
305    import xmlrpclib
307    def python_logo():
308         handle = open("python_logo.jpg")
309         return xmlrpclib.Binary(handle.read())
310         handle.close()
312    server = SimpleXMLRPCServer(("localhost", 8000))
313    print "Listening on port 8000..."
314    server.register_function(python_logo, 'python_logo')
316    server.serve_forever()
318 The client gets the image and saves it to a file::
320    import xmlrpclib
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()
327 .. _fault-objects:
329 Fault Objects
330 -------------
332 A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
333 objects have the following members:
336 .. attribute:: Fault.faultCode
338    A string indicating the fault type.
341 .. attribute:: Fault.faultString
343    A string containing a diagnostic message associated with the fault.
345 In the following example we're going to intentionally cause a :exc:`Fault` by
346 returning a complex type object.  The server code::
348    from SimpleXMLRPCServer import SimpleXMLRPCServer
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
355    server = SimpleXMLRPCServer(("localhost", 8000))
356    print "Listening on port 8000..."
357    server.register_function(add, 'add')
359    server.serve_forever()
361 The client code for the preceding server::
363    import xmlrpclib
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
375 .. _protocol-error-objects:
377 ProtocolError Objects
378 ---------------------
380 A :class:`ProtocolError` object describes a protocol error in the underlying
381 transport layer (such as a 404 'not found' error if the server named by the URI
382 does not exist).  It has the following members:
385 .. attribute:: ProtocolError.url
387    The URI or URL that triggered the error.
390 .. attribute:: ProtocolError.errcode
392    The error code.
395 .. attribute:: ProtocolError.errmsg
397    The error message or diagnostic string.
400 .. attribute:: ProtocolError.headers
402    A string containing the headers of the HTTP/HTTPS request that triggered the
403    error.
405 In the following example we're going to intentionally cause a :exc:`ProtocolError`
406 by providing an invalid URI::
408    import xmlrpclib
410    # create a ServerProxy with an invalid URI
411    proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
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
422 MultiCall Objects
423 -----------------
425 .. versionadded:: 2.4
427 In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
428 encapsulate multiple calls to a remote server into a single request.
431 .. class:: MultiCall(server)
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
438    is a :term:`generator`; iterating over this generator yields the individual
439    results.
441 A usage example of this class follows.  The server code ::
443    from SimpleXMLRPCServer import SimpleXMLRPCServer
445    def add(x,y):
446        return x+y
448    def subtract(x, y):
449        return x-y
451    def multiply(x, y):
452        return x*y
454    def divide(x, y):
455        return x/y
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()
467 The client code for the preceding server::
469    import xmlrpclib
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()
479    print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
482 Convenience Functions
483 ---------------------
486 .. function:: boolean(value)
488    Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
489    ``False``.
492 .. function:: dumps(params[, methodname[,  methodresponse[, encoding[, allow_none]]]])
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*.
503 .. function:: loads(data[, use_datetime])
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.
515    .. versionchanged:: 2.5
516       The *use_datetime* flag was added.
519 .. _xmlrpc-client-example:
521 Example of Client Usage
522 -----------------------
526    # simple test program (from the XML-RPC specification)
527    from xmlrpclib import ServerProxy, Error
529    # server = ServerProxy("http://localhost:8000") # local server
530    server = ServerProxy("http://betty.userland.com")
532    print server
534    try:
535        print server.examples.getStateName(41)
536    except Error, v:
537        print "ERROR", v
539 To access an XML-RPC server through a proxy, you need to define  a custom
540 transport.  The following example shows how:
542 .. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
546    import xmlrpclib, httplib
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)
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()
566 Example of Client and Server Usage
567 ----------------------------------
569 See :ref:`simplexmlrpcserver-example`.