blob: cd507c46e431c3a6e792947403c3a4d1efbde841 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
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
10
11.. % Not everything is documented yet. It might be good to describe
12.. % 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.
21
22
23.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]])
24
25 A :class:`ServerProxy` instance is an object that manages communication with a
26 remote XML-RPC server. The required first argument is a URI (Uniform Resource
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
35 all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
36 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.
38 :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time`
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
50 The returned instance is a proxy object with methods that can be used to invoke
51 corresponding RPC calls on the remote server. If the remote server supports the
52 introspection API, the proxy can also be used to query the remote server for the
53 methods it supports (service discovery) and fetch other server-associated
54 metadata.
55
56 :class:`ServerProxy` instance methods take Python basic types and objects as
57 arguments and return Python basic types and classes. Types that are conformable
58 (e.g. that can be marshalled through XML), include the following (and except
59 where noted, they are unmarshalled as the same Python type):
60
61 +---------------------------------+---------------------------------------------+
62 | Name | Meaning |
63 +=================================+=============================================+
64 | :const:`boolean` | The :const:`True` and :const:`False` |
65 | | constants |
66 +---------------------------------+---------------------------------------------+
67 | :const:`integers` | Pass in directly |
68 +---------------------------------+---------------------------------------------+
69 | :const:`floating-point numbers` | Pass in directly |
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, |
78 | | values may be any conformable type. Objects |
79 | | of user-defined classes can be passed in; |
80 | | only their *__dict__* attribute is |
81 | | transmitted. |
82 +---------------------------------+---------------------------------------------+
83 | :const:`dates` | in seconds since the epoch (pass in an |
84 | | instance of the :class:`DateTime` class) or |
85 | | a :class:`datetime.datetime`, |
86 | | :class:`datetime.date` or |
87 | | :class:`datetime.time` instance |
88 +---------------------------------+---------------------------------------------+
89 | :const:`binary data` | pass in an instance of the :class:`Binary` |
90 | | wrapper class |
91 +---------------------------------+---------------------------------------------+
92
93 This is the full set of data types supported by XML-RPC. Method calls may also
94 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
95 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
96 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
97 :exc:`Error`. Note that even though starting with Python 2.2 you can subclass
98 builtin types, the xmlrpclib module currently does not marshal instances of such
99 subclasses.
100
101 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
102 will be automatically escaped. However, it's the caller's responsibility to
103 ensure that the string is free of characters that aren't allowed in XML, such as
104 the control characters with ASCII values between 0 and 31 (except, of course,
105 tab, newline and carriage return); failing to do this will result in an XML-RPC
106 request that isn't well-formed XML. If you have to pass arbitrary strings via
107 XML-RPC, use the :class:`Binary` wrapper class described below.
108
109 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
110 compatibility. New code should use :class:`ServerProxy`.
111
112 .. versionchanged:: 2.5
113 The *use_datetime* flag was added.
114
115 .. versionchanged:: 2.6
116 Instances of new-style classes can be passed in if they have an *__dict__*
117 attribute and don't have a base class that is marshalled in a 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 operation and client software in several languages.
124 Contains pretty much everything an XML-RPC client developer needs to know.
125
126 `XML-RPC Hacks page <http://xmlrpc-c.sourceforge.net/hacks.php>`_
127 Extensions for various open-source libraries to support introspection and
128 multicall.
129
130
131.. _serverproxy-objects:
132
133ServerProxy Objects
134-------------------
135
136A :class:`ServerProxy` instance has a method corresponding to each remote
137procedure call accepted by the XML-RPC server. Calling the method performs an
138RPC, dispatched by both name and argument signature (e.g. the same method name
139can be overloaded with multiple argument signatures). The RPC finishes by
140returning a value, which may be either returned data in a conformant type or a
141:class:`Fault` or :class:`ProtocolError` object indicating an error.
142
143Servers that support the XML introspection API support some common methods
144grouped under the reserved :attr:`system` member:
145
146
147.. method:: ServerProxy.system.listMethods()
148
149 This method returns a list of strings, one for each (non-system) method
150 supported by the XML-RPC server.
151
152
153.. method:: ServerProxy.system.methodSignature(name)
154
155 This method takes one parameter, the name of a method implemented by the XML-RPC
156 server.It returns an array of possible signatures for this method. A signature
157 is an array of types. The first of these types is the return type of the method,
158 the rest are parameters.
159
160 Because multiple signatures (ie. overloading) is permitted, this method returns
161 a list of signatures rather than a singleton.
162
163 Signatures themselves are restricted to the top level parameters expected by a
164 method. For instance if a method expects one array of structs as a parameter,
165 and it returns a string, its signature is simply "string, array". If it expects
166 three integers and returns a string, its signature is "string, int, int, int".
167
168 If no signature is defined for the method, a non-array value is returned. In
169 Python this means that the type of the returned value will be something other
170 that list.
171
172
173.. method:: ServerProxy.system.methodHelp(name)
174
175 This method takes one parameter, the name of a method implemented by the XML-RPC
176 server. It returns a documentation string describing the use of that method. If
177 no such string is available, an empty string is returned. The documentation
178 string may contain HTML markup.
179
180Introspection methods are currently supported by servers written in PHP, C and
181Microsoft .NET. Partial introspection support is included in recent updates to
182UserLand Frontier. Introspection support for Perl, Python and Java is available
183at the `XML-RPC Hacks <http://xmlrpc-c.sourceforge.net/hacks.php>`_ page.
184
185
186.. _boolean-objects:
187
188Boolean Objects
189---------------
190
191This class may be initialized from any Python value; the instance returned
192depends only on its truth value. It supports various Python operators through
193:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__bool__`
194methods, all implemented in the obvious ways.
195
196It also has the following method, supported mainly for internal use by the
197unmarshalling code:
198
199
200.. method:: Boolean.encode(out)
201
202 Write the XML-RPC encoding of this Boolean item to the out stream object.
203
204
205.. _datetime-objects:
206
207DateTime Objects
208----------------
209
210This class may be initialized with seconds since the epoch, a time tuple, an ISO
2118601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
212or :class:`datetime.time` instance. It has the following methods, supported
213mainly for internal use by the marshalling/unmarshalling code:
214
215
216.. method:: DateTime.decode(string)
217
218 Accept a string as the instance's new time value.
219
220
221.. method:: DateTime.encode(out)
222
223 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
224 object.
225
226It also supports certain of Python's built-in operators through :meth:`__cmp__`
227and :meth:`__repr__` methods.
228
229
230.. _binary-objects:
231
232Binary Objects
233--------------
234
235This class may be initialized from string data (which may include NULs). The
236primary access to the content of a :class:`Binary` object is provided by an
237attribute:
238
239
240.. attribute:: Binary.data
241
242 The binary data encapsulated by the :class:`Binary` instance. The data is
243 provided as an 8-bit string.
244
245:class:`Binary` objects have the following methods, supported mainly for
246internal use by the marshalling/unmarshalling code:
247
248
249.. method:: Binary.decode(string)
250
251 Accept a base64 string and decode it as the instance's new data.
252
253
254.. method:: Binary.encode(out)
255
256 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
257
258It also supports certain of Python's built-in operators through a
259:meth:`__cmp__` method.
260
261
262.. _fault-objects:
263
264Fault Objects
265-------------
266
267A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
268objects have the following members:
269
270
271.. attribute:: Fault.faultCode
272
273 A string indicating the fault type.
274
275
276.. attribute:: Fault.faultString
277
278 A string containing a diagnostic message associated with the fault.
279
280
281.. _protocol-error-objects:
282
283ProtocolError Objects
284---------------------
285
286A :class:`ProtocolError` object describes a protocol error in the underlying
287transport layer (such as a 404 'not found' error if the server named by the URI
288does not exist). It has the following members:
289
290
291.. attribute:: ProtocolError.url
292
293 The URI or URL that triggered the error.
294
295
296.. attribute:: ProtocolError.errcode
297
298 The error code.
299
300
301.. attribute:: ProtocolError.errmsg
302
303 The error message or diagnostic string.
304
305
306.. attribute:: ProtocolError.headers
307
308 A string containing the headers of the HTTP/HTTPS request that triggered the
309 error.
310
311
312MultiCall Objects
313-----------------
314
315.. versionadded:: 2.4
316
317In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
318encapsulate multiple calls to a remote server into a single request.
319
320
321.. class:: MultiCall(server)
322
323 Create an object used to boxcar method calls. *server* is the eventual target of
324 the call. Calls can be made to the result object, but they will immediately
325 return ``None``, and only store the call name and parameters in the
326 :class:`MultiCall` object. Calling the object itself causes all stored calls to
327 be transmitted as a single ``system.multicall`` request. The result of this call
328 is a generator; iterating over this generator yields the individual results.
329
330A usage example of this class is ::
331
332 multicall = MultiCall(server_proxy)
333 multicall.add(2,3)
334 multicall.get_address("Guido")
335 add_result, address = multicall()
336
337
338Convenience Functions
339---------------------
340
341
342.. function:: boolean(value)
343
344 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
345 ``False``.
346
347
348.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
349
350 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
351 is true. *params* can be either a tuple of arguments or an instance of the
352 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
353 can be returned, meaning that *params* must be of length 1. *encoding*, if
354 supplied, is the encoding to use in the generated XML; the default is UTF-8.
355 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
356 it via an extension, provide a true value for *allow_none*.
357
358
359.. function:: loads(data[, use_datetime])
360
361 Convert an XML-RPC request or response into Python objects, a ``(params,
362 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
363 ``None`` if no method name is present in the packet. If the XML-RPC packet
364 represents a fault condition, this function will raise a :exc:`Fault` exception.
365 The *use_datetime* flag can be used to cause date/time values to be presented as
366 :class:`datetime.datetime` objects; this is false by default. Note that even if
367 you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
368 objects, they are converted to :class:`DateTime` objects internally, so only
369 :class:`datetime.datetime` objects will be returned.
370
371 .. versionchanged:: 2.5
372 The *use_datetime* flag was added.
373
374
375.. _xmlrpc-client-example:
376
377Example of Client Usage
378-----------------------
379
380::
381
382 # simple test program (from the XML-RPC specification)
383 from xmlrpclib import ServerProxy, Error
384
385 # server = ServerProxy("http://localhost:8000") # local server
386 server = ServerProxy("http://betty.userland.com")
387
388 print server
389
390 try:
391 print server.examples.getStateName(41)
392 except Error as v:
393 print "ERROR", v
394
395To access an XML-RPC server through a proxy, you need to define a custom
396transport. The following example, written by NoboNobo, shows how:
397
398.. % fill in original author's name if we ever learn it
399
400.. % Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
401
402::
403
404 import xmlrpclib, httplib
405
406 class ProxiedTransport(xmlrpclib.Transport):
407 def set_proxy(self, proxy):
408 self.proxy = proxy
409 def make_connection(self, host):
410 self.realhost = host
411 h = httplib.HTTP(self.proxy)
412 return h
413 def send_request(self, connection, handler, request_body):
414 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
415 def send_host(self, connection, host):
416 connection.putheader('Host', self.realhost)
417
418 p = ProxiedTransport()
419 p.set_proxy('proxy-server:8080')
420 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
421 print server.currentTime.getCurrentTime()
422