blob: 1faa891e8dc8c16d15fd09890f4ecb65f6df88a5 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandla7395032007-10-21 12:15:05 +0000116 Instances of :term:`new-style class`\es can be passed in if they have an
117 *__dict__* attribute and don't have a base class that is marshalled in a
118 special way.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119
120
121.. seealso::
122
123 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
124 A good description of XML operation and client software in several languages.
125 Contains pretty much everything an XML-RPC client developer needs to know.
126
127 `XML-RPC Hacks page <http://xmlrpc-c.sourceforge.net/hacks.php>`_
128 Extensions for various open-source libraries to support introspection and
129 multicall.
130
131
132.. _serverproxy-objects:
133
134ServerProxy Objects
135-------------------
136
137A :class:`ServerProxy` instance has a method corresponding to each remote
138procedure call accepted by the XML-RPC server. Calling the method performs an
139RPC, dispatched by both name and argument signature (e.g. the same method name
140can be overloaded with multiple argument signatures). The RPC finishes by
141returning a value, which may be either returned data in a conformant type or a
142:class:`Fault` or :class:`ProtocolError` object indicating an error.
143
144Servers that support the XML introspection API support some common methods
145grouped under the reserved :attr:`system` member:
146
147
148.. method:: ServerProxy.system.listMethods()
149
150 This method returns a list of strings, one for each (non-system) method
151 supported by the XML-RPC server.
152
153
154.. method:: ServerProxy.system.methodSignature(name)
155
156 This method takes one parameter, the name of a method implemented by the XML-RPC
157 server.It returns an array of possible signatures for this method. A signature
158 is an array of types. The first of these types is the return type of the method,
159 the rest are parameters.
160
161 Because multiple signatures (ie. overloading) is permitted, this method returns
162 a list of signatures rather than a singleton.
163
164 Signatures themselves are restricted to the top level parameters expected by a
165 method. For instance if a method expects one array of structs as a parameter,
166 and it returns a string, its signature is simply "string, array". If it expects
167 three integers and returns a string, its signature is "string, int, int, int".
168
169 If no signature is defined for the method, a non-array value is returned. In
170 Python this means that the type of the returned value will be something other
171 that list.
172
173
174.. method:: ServerProxy.system.methodHelp(name)
175
176 This method takes one parameter, the name of a method implemented by the XML-RPC
177 server. It returns a documentation string describing the use of that method. If
178 no such string is available, an empty string is returned. The documentation
179 string may contain HTML markup.
180
181Introspection methods are currently supported by servers written in PHP, C and
182Microsoft .NET. Partial introspection support is included in recent updates to
183UserLand Frontier. Introspection support for Perl, Python and Java is available
184at the `XML-RPC Hacks <http://xmlrpc-c.sourceforge.net/hacks.php>`_ page.
185
186
187.. _boolean-objects:
188
189Boolean Objects
190---------------
191
192This class may be initialized from any Python value; the instance returned
193depends only on its truth value. It supports various Python operators through
194:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
195methods, all implemented in the obvious ways.
196
197It also has the following method, supported mainly for internal use by the
198unmarshalling code:
199
200
201.. method:: Boolean.encode(out)
202
203 Write the XML-RPC encoding of this Boolean item to the out stream object.
204
205
206.. _datetime-objects:
207
208DateTime Objects
209----------------
210
211This class may be initialized with seconds since the epoch, a time tuple, an ISO
2128601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
213or :class:`datetime.time` instance. It has the following methods, supported
214mainly for internal use by the marshalling/unmarshalling code:
215
216
217.. method:: DateTime.decode(string)
218
219 Accept a string as the instance's new time value.
220
221
222.. method:: DateTime.encode(out)
223
224 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
225 object.
226
227It also supports certain of Python's built-in operators through :meth:`__cmp__`
228and :meth:`__repr__` methods.
229
230
231.. _binary-objects:
232
233Binary Objects
234--------------
235
236This class may be initialized from string data (which may include NULs). The
237primary access to the content of a :class:`Binary` object is provided by an
238attribute:
239
240
241.. attribute:: Binary.data
242
243 The binary data encapsulated by the :class:`Binary` instance. The data is
244 provided as an 8-bit string.
245
246:class:`Binary` objects have the following methods, supported mainly for
247internal use by the marshalling/unmarshalling code:
248
249
250.. method:: Binary.decode(string)
251
252 Accept a base64 string and decode it as the instance's new data.
253
254
255.. method:: Binary.encode(out)
256
257 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
258
259It also supports certain of Python's built-in operators through a
260:meth:`__cmp__` method.
261
262
263.. _fault-objects:
264
265Fault Objects
266-------------
267
268A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
269objects have the following members:
270
271
272.. attribute:: Fault.faultCode
273
274 A string indicating the fault type.
275
276
277.. attribute:: Fault.faultString
278
279 A string containing a diagnostic message associated with the fault.
280
281
282.. _protocol-error-objects:
283
284ProtocolError Objects
285---------------------
286
287A :class:`ProtocolError` object describes a protocol error in the underlying
288transport layer (such as a 404 'not found' error if the server named by the URI
289does not exist). It has the following members:
290
291
292.. attribute:: ProtocolError.url
293
294 The URI or URL that triggered the error.
295
296
297.. attribute:: ProtocolError.errcode
298
299 The error code.
300
301
302.. attribute:: ProtocolError.errmsg
303
304 The error message or diagnostic string.
305
306
307.. attribute:: ProtocolError.headers
308
309 A string containing the headers of the HTTP/HTTPS request that triggered the
310 error.
311
312
313MultiCall Objects
314-----------------
315
316.. versionadded:: 2.4
317
318In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
319encapsulate multiple calls to a remote server into a single request.
320
321
322.. class:: MultiCall(server)
323
324 Create an object used to boxcar method calls. *server* is the eventual target of
325 the call. Calls can be made to the result object, but they will immediately
326 return ``None``, and only store the call name and parameters in the
327 :class:`MultiCall` object. Calling the object itself causes all stored calls to
328 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000329 is a :term:`generator`; iterating over this generator yields the individual
330 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000331
332A usage example of this class is ::
333
334 multicall = MultiCall(server_proxy)
335 multicall.add(2,3)
336 multicall.get_address("Guido")
337 add_result, address = multicall()
338
339
340Convenience Functions
341---------------------
342
343
344.. function:: boolean(value)
345
346 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
347 ``False``.
348
349
350.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
351
352 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
353 is true. *params* can be either a tuple of arguments or an instance of the
354 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
355 can be returned, meaning that *params* must be of length 1. *encoding*, if
356 supplied, is the encoding to use in the generated XML; the default is UTF-8.
357 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
358 it via an extension, provide a true value for *allow_none*.
359
360
361.. function:: loads(data[, use_datetime])
362
363 Convert an XML-RPC request or response into Python objects, a ``(params,
364 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
365 ``None`` if no method name is present in the packet. If the XML-RPC packet
366 represents a fault condition, this function will raise a :exc:`Fault` exception.
367 The *use_datetime* flag can be used to cause date/time values to be presented as
368 :class:`datetime.datetime` objects; this is false by default. Note that even if
369 you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
370 objects, they are converted to :class:`DateTime` objects internally, so only
371 :class:`datetime.datetime` objects will be returned.
372
373 .. versionchanged:: 2.5
374 The *use_datetime* flag was added.
375
376
377.. _xmlrpc-client-example:
378
379Example of Client Usage
380-----------------------
381
382::
383
384 # simple test program (from the XML-RPC specification)
385 from xmlrpclib import ServerProxy, Error
386
387 # server = ServerProxy("http://localhost:8000") # local server
388 server = ServerProxy("http://betty.userland.com")
389
390 print server
391
392 try:
393 print server.examples.getStateName(41)
394 except Error, v:
395 print "ERROR", v
396
397To access an XML-RPC server through a proxy, you need to define a custom
398transport. The following example, written by NoboNobo, shows how:
399
400.. % fill in original author's name if we ever learn it
401
402.. % Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
403
404::
405
406 import xmlrpclib, httplib
407
408 class ProxiedTransport(xmlrpclib.Transport):
409 def set_proxy(self, proxy):
410 self.proxy = proxy
411 def make_connection(self, host):
412 self.realhost = host
413 h = httplib.HTTP(self.proxy)
414 return h
415 def send_request(self, connection, handler, request_body):
416 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
417 def send_host(self, connection, host):
418 connection.putheader('Host', self.realhost)
419
420 p = ProxiedTransport()
421 p.set_proxy('proxy-server:8080')
422 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
423 print server.currentTime.getCurrentTime()
424