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