rest25/library/xmlrpclib.rst => rest262/library/xmlrpclib.rst
n1- 
2:mod:`xmlrpclib` --- XML-RPC client access
3==========================================
4
5.. module:: xmlrpclib
6   :synopsis: XML-RPC client access.
7.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
8.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
9
n9+.. 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.
10
n14+ 
11-.. % Not everything is documented yet.  It might be good to describe
15+.. XXX Not everything is documented yet.  It might be good to describe
12-.. % Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
16+   Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
13
14.. versionadded:: 2.2
15
16XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
17transport.  With it, a client can call methods with parameters on a remote
18server (the server is named by a URI) and get back structured data.  This module
19supports writing XML-RPC client code; it handles all the details of translating
20between conformable Python objects and XML on the wire.
27   Indicator), and will normally be the URL of the server.  The optional second
28   argument is a transport factory instance; by default it is an internal
29   :class:`SafeTransport` instance for https: URLs and an internal HTTP
30   :class:`Transport` instance otherwise.  The optional third argument is an
31   encoding, by default UTF-8. The optional fourth argument is a debugging flag.
32   If *allow_none* is true,  the Python constant ``None`` will be translated into
33   XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
34   a commonly-used extension to the XML-RPC specification, but isn't supported by
n35-   all clients and servers; see `<http://ontosys.com/xml-rpc/extensions.php>`_ for
n39+   all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
36-   a description.  The *use_datetime* flag can be used to cause date/time values to
40+   description.  The *use_datetime* flag can be used to cause date/time values to
37   be presented as :class:`datetime.datetime` objects; this is false by default.
n38-   :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time`
n42+   :class:`datetime.datetime` objects may be passed to calls.
39-   objects may be passed to calls.  :class:`datetime.date` objects are converted
40-   with a time of "00:00:00". :class:`datetime.time` objects are converted using
41-   today's date.
42
43   Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
44   Basic Authentication: ``http://user:pass@host:port/path``.  The  ``user:pass``
45   portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
46   the remote server as part of the connection process when invoking an XML-RPC
47   method.  You only need to use this if the remote server requires a Basic
48   Authentication user and password.
49
70   +---------------------------------+---------------------------------------------+
71   | :const:`strings`                | Pass in directly                            |
72   +---------------------------------+---------------------------------------------+
73   | :const:`arrays`                 | Any Python sequence type containing         |
74   |                                 | conformable elements. Arrays are returned   |
75   |                                 | as lists                                    |
76   +---------------------------------+---------------------------------------------+
77   | :const:`structures`             | A Python dictionary. Keys must be strings,  |
n78-   |                                 | values may be any conformable type.         |
n79+   |                                 | values may be any conformable type. Objects |
80+   |                                 | of user-defined classes can be passed in;   |
81+   |                                 | only their *__dict__* attribute is          |
82+   |                                 | transmitted.                                |
79   +---------------------------------+---------------------------------------------+
80   | :const:`dates`                  | in seconds since the epoch (pass in an      |
81   |                                 | instance of the :class:`DateTime` class) or |
n82-   |                                 | a :class:`datetime.datetime`,               |
83-   |                                 | :class:`datetime.date` or                   |
84-   |                                 | :class:`datetime.time` instance             |
86+   |                                 | a :class:`datetime.datetime` instance.      |
85   +---------------------------------+---------------------------------------------+
86   | :const:`binary data`            | pass in an instance of the :class:`Binary`  |
87   |                                 | wrapper class                               |
88   +---------------------------------+---------------------------------------------+
89
90   This is the full set of data types supported by XML-RPC.  Method calls may also
91   raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
92   :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
93   Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
94   :exc:`Error`.  Note that even though starting with Python 2.2 you can subclass
95   builtin types, the xmlrpclib module currently does not marshal instances of such
96   subclasses.
97
98   When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
99   will be automatically escaped.  However, it's the caller's responsibility to
100   ensure that the string is free of characters that aren't allowed in XML, such as
n101-   the control characters with ASCII values between 0 and 31failing to do this
n103+   the control characters with ASCII values between 0 and 31 (except, of course,
102-   will result in an XML-RPC request that isn't well-formed XML.  If you have to
104+   tab, newline and carriage return); failing to do this will result in an XML-RPC
103-   pass arbitrary strings via XML-RPC, use the :class:`Binary` wrapper class
105+   request that isn't well-formed XML.  If you have to pass arbitrary strings via
104-   described below.
106+   XML-RPC, use the :class:`Binary` wrapper class described below.
105
106   :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
107   compatibility.  New code should use :class:`ServerProxy`.
108
109   .. versionchanged:: 2.5
110      The *use_datetime* flag was added.
111
n114+   .. 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+ 
112
113.. seealso::
114
115   `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
n116-      A good description of XML operation and client software in several languages.
n123+      A good description of XML-RPC operation and client software in several languages.
117      Contains pretty much everything an XML-RPC client developer needs to know.
118
n119-   `XML-RPC Hacks page <http://xmlrpc-c.sourceforge.net/hacks.php>`_
n126+   `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
120-      Extensions for various open-source libraries to support introspection and
127+      Describes the XML-RPC protocol extension for introspection.
121-      multicall.
122
n129+   `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."
123
124.. _serverproxy-objects:
125
126ServerProxy Objects
127-------------------
128
129A :class:`ServerProxy` instance has a method corresponding to each remote
130procedure call accepted by the XML-RPC server.  Calling the method performs an
132can be overloaded with multiple argument signatures).  The RPC finishes by
133returning a value, which may be either returned data in a conformant type or a
134:class:`Fault` or :class:`ProtocolError` object indicating an error.
135
136Servers that support the XML introspection API support some common methods
137grouped under the reserved :attr:`system` member:
138
139
n140-.. method:: XXX Class.system.listMethods()
n154+.. method:: ServerProxy.system.listMethods()
141
142   This method returns a list of strings, one for each (non-system) method
143   supported by the XML-RPC server.
144
145
n146-.. method:: XXX Class.system.methodSignature(name)
n160+.. method:: ServerProxy.system.methodSignature(name)
147
148   This method takes one parameter, the name of a method implemented by the XML-RPC
149   server.It returns an array of possible signatures for this method. A signature
150   is an array of types. The first of these types is the return type of the method,
151   the rest are parameters.
152
153   Because multiple signatures (ie. overloading) is permitted, this method returns
154   a list of signatures rather than a singleton.
158   and it returns a string, its signature is simply "string, array". If it expects
159   three integers and returns a string, its signature is "string, int, int, int".
160
161   If no signature is defined for the method, a non-array value is returned. In
162   Python this means that the type of the returned  value will be something other
163   that list.
164
165
n166-.. method:: XXX Class.system.methodHelp(name)
n180+.. method:: ServerProxy.system.methodHelp(name)
167
168   This method takes one parameter, the name of a method implemented by the XML-RPC
169   server.  It returns a documentation string describing the use of that method. If
170   no such string is available, an empty string is returned. The documentation
171   string may contain HTML markup.
172
n173-Introspection methods are currently supported by servers written in PHP, C and
174-Microsoft .NET. Partial introspection support is included in recent updates to
175-UserLand Frontier. Introspection support for Perl, Python and Java is available
176-at the `XML-RPC Hacks <http://xmlrpc-c.sourceforge.net/hacks.php>`_ page.
177- 
178
179.. _boolean-objects:
180
181Boolean Objects
182---------------
183
184This class may be initialized from any Python value; the instance returned
185depends only on its truth value.  It supports various Python operators through
186:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
187methods, all implemented in the obvious ways.
188
189It also has the following method, supported mainly for internal use by the
190unmarshalling code:
191
192
n193-.. method:: XXX Class.encode(out)
n202+.. method:: Boolean.encode(out)
194
195   Write the XML-RPC encoding of this Boolean item to the out stream object.
196
n206+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))
197
198.. _datetime-objects:
199
200DateTime Objects
201----------------
202
n203-This class may be initialized with seconds since the epoch, a time tuple, an ISO
n232+This class may be initialized with seconds since the epoch, a time
204-8601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
233+tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
205-or :class:`datetime.time` instance.  It has the following methods, supported
234+instance.  It has the following methods, supported mainly for internal
206-mainly for internal use by the marshalling/unmarshalling code:
235+use by the marshalling/unmarshalling code:
207
208
n209-.. method:: XXX Class.decode(string)
n238+.. method:: DateTime.decode(string)
210
211   Accept a string as the instance's new time value.
212
213
n214-.. method:: XXX Class.encode(out)
n243+.. method:: DateTime.encode(out)
215
216   Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
217   object.
218
219It also supports certain of Python's built-in operators through  :meth:`__cmp__`
220and :meth:`__repr__` methods.
221
n251+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")
222
223.. _binary-objects:
224
225Binary Objects
226--------------
227
228This class may be initialized from string data (which may include NULs). The
229primary access to the content of a :class:`Binary` object is provided by an
243
244   Accept a base64 string and decode it as the instance's new data.
245
246
247.. method:: Binary.encode(out)
248
249   Write the XML-RPC base 64 encoding of this binary item to the out stream object.
250
n306+   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+ 
251It also supports certain of Python's built-in operators through a
252:meth:`__cmp__` method.
253
n314+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)
254
255.. _fault-objects:
256
257Fault Objects
258-------------
259
260A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
261objects have the following members:
262
263
n264-.. attribute:: XXX Class.faultCode
n347+.. attribute:: Fault.faultCode
265
266   A string indicating the fault type.
267
268
n269-.. attribute:: XXX Class.faultString
n352+.. attribute:: Fault.faultString
270
271   A string containing a diagnostic message associated with the fault.
n355+ 
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+ 
272
273
274.. _protocol-error-objects:
275
276ProtocolError Objects
277---------------------
278
279A :class:`ProtocolError` object describes a protocol error in the underlying
280transport layer (such as a 404 'not found' error if the server named by the URI
281does not exist).  It has the following members:
282
283
n284-.. attribute:: XXX Class.url
n396+.. attribute:: ProtocolError.url
285
286   The URI or URL that triggered the error.
287
288
n289-.. attribute:: XXX Class.errcode
n401+.. attribute:: ProtocolError.errcode
290
291   The error code.
292
293
n294-.. attribute:: XXX Class.errmsg
n406+.. attribute:: ProtocolError.errmsg
295
296   The error message or diagnostic string.
297
298
n299-.. attribute:: XXX Class.headers
n411+.. attribute:: ProtocolError.headers
300
301   A string containing the headers of the HTTP/HTTPS request that triggered the
302   error.
303
n416+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
304
305MultiCall Objects
306-----------------
307
308.. versionadded:: 2.4
309
n310-In `<http://www.xmlrpc.com/discuss/msgReader%241208>`_, an approach is presented
n438+In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
311-to encapsulate multiple calls to a remote server into a single request.
439+encapsulate multiple calls to a remote server into a single request.
312
313
314.. class:: MultiCall(server)
315
316   Create an object used to boxcar method calls. *server* is the eventual target of
317   the call. Calls can be made to the result object, but they will immediately
n318-   return *None*, and only store the call name and parameters in the
n446+   return ``None``, and only store the call name and parameters in the
319   :class:`MultiCall` object. Calling the object itself causes all stored calls to
320   be transmitted as a single ``system.multicall`` request. The result of this call
n321-   is a generator; iterating over this generator yields the individual results.
n449+   is a :term:`generator`; iterating over this generator yields the individual
450+   results.
322
n323-A usage example of this class is ::
n452+A usage example of this class follows.  The server code ::
324
n454+   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/")
325-   multicall = MultiCall(server_proxy)
483+   multicall = xmlrpclib.MultiCall(proxy)
326-   multicall.add(2,3)
484+   multicall.add(7,3)
327-   multicall.get_address("Guido")
485+   multicall.subtract(7,3)
486+   multicall.multiply(7,3)
487+   multicall.divide(7,3)
328-   add_result, address = multicall()
488+   result = multicall()
489+ 
490+   print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
329
330
331Convenience Functions
332---------------------
333
334
335.. function:: boolean(value)
336
351
352.. function:: loads(data[, use_datetime])
353
354   Convert an XML-RPC request or response into Python objects, a ``(params,
355   methodname)``.  *params* is a tuple of argument; *methodname* is a string, or
356   ``None`` if no method name is present in the packet. If the XML-RPC packet
357   represents a fault condition, this function will raise a :exc:`Fault` exception.
358   The *use_datetime* flag can be used to cause date/time values to be presented as
n359-   :class:`datetime.datetime` objects; this is false by default. Note that even if
n521+   :class:`datetime.datetime` objects; this is false by default.
360-   you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
361-   objects, they are converted to :class:`DateTime` objects internally, so only
362-   :class:`datetime.datetime` objects will be returned.
363
364   .. versionchanged:: 2.5
365      The *use_datetime* flag was added.
366
367
368.. _xmlrpc-client-example:
369
370Example of Client Usage
381   print server
382
383   try:
384       print server.examples.getStateName(41)
385   except Error, v:
386       print "ERROR", v
387
388To access an XML-RPC server through a proxy, you need to define  a custom
n389-transport.  The following example,  written by NoboNobo, shows how:
n548+transport.  The following example shows how:
390
n391-.. % fill in original author's name if we ever learn it
392- 
393-.. % Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
550+.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
394
395::
396
397   import xmlrpclib, httplib
398
399   class ProxiedTransport(xmlrpclib.Transport):
400       def set_proxy(self, proxy):
401           self.proxy = proxy
402       def make_connection(self, host):
403           self.realhost = host
n404-        h = httplib.HTTP(self.proxy)
n561+           h = httplib.HTTP(self.proxy)
405-        return h
562+           return h
406       def send_request(self, connection, handler, request_body):
407           connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
408       def send_host(self, connection, host):
409           connection.putheader('Host', self.realhost)
410
411   p = ProxiedTransport()
412   p.set_proxy('proxy-server:8080')
413   server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
414   print server.currentTime.getCurrentTime()
415
t573+ 
574+Example of Client and Server Usage
575+----------------------------------
576+ 
577+See :ref:`simplexmlrpcserver-example`.
578+ 
579+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op