blob: 9dd6c0e3b6034bf5e7e764e96cc152696c246bc7 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001: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
Georg Brandlb19be572007-12-29 10:57:00 +000010.. XXX Not everything is documented yet. It might be good to describe
11 Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
Georg Brandl8ec7f652007-08-15 14:28:01 +000012
13.. versionadded:: 2.2
14
15XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
16transport. With it, a client can call methods with parameters on a remote
17server (the server is named by a URI) and get back structured data. This module
18supports writing XML-RPC client code; it handles all the details of translating
19between conformable Python objects and XML on the wire.
20
21
22.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]])
23
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.
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000037 :class:`datetime.datetime` objects may be passed to calls.
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
40 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
41 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
42 the remote server as part of the connection process when invoking an XML-RPC
43 method. You only need to use this if the remote server requires a Basic
44 Authentication user and password.
45
46 The returned instance is a proxy object with methods that can be used to invoke
47 corresponding RPC calls on the remote server. If the remote server supports the
48 introspection API, the proxy can also be used to query the remote server for the
49 methods it supports (service discovery) and fetch other server-associated
50 metadata.
51
52 :class:`ServerProxy` instance methods take Python basic types and objects as
53 arguments and return Python basic types and classes. Types that are conformable
54 (e.g. that can be marshalled through XML), include the following (and except
55 where noted, they are unmarshalled as the same Python type):
56
57 +---------------------------------+---------------------------------------------+
58 | Name | Meaning |
59 +=================================+=============================================+
60 | :const:`boolean` | The :const:`True` and :const:`False` |
61 | | constants |
62 +---------------------------------+---------------------------------------------+
63 | :const:`integers` | Pass in directly |
64 +---------------------------------+---------------------------------------------+
65 | :const:`floating-point numbers` | Pass in directly |
66 +---------------------------------+---------------------------------------------+
67 | :const:`strings` | Pass in directly |
68 +---------------------------------+---------------------------------------------+
69 | :const:`arrays` | Any Python sequence type containing |
70 | | conformable elements. Arrays are returned |
71 | | as lists |
72 +---------------------------------+---------------------------------------------+
73 | :const:`structures` | A Python dictionary. Keys must be strings, |
74 | | values may be any conformable type. Objects |
75 | | of user-defined classes can be passed in; |
76 | | only their *__dict__* attribute is |
77 | | transmitted. |
78 +---------------------------------+---------------------------------------------+
79 | :const:`dates` | in seconds since the epoch (pass in an |
80 | | instance of the :class:`DateTime` class) or |
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000081 | | a :class:`datetime.datetime` instance. |
Georg Brandl8ec7f652007-08-15 14:28:01 +000082 +---------------------------------+---------------------------------------------+
83 | :const:`binary data` | pass in an instance of the :class:`Binary` |
84 | | wrapper class |
85 +---------------------------------+---------------------------------------------+
86
87 This is the full set of data types supported by XML-RPC. Method calls may also
88 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
89 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
90 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
91 :exc:`Error`. Note that even though starting with Python 2.2 you can subclass
92 builtin types, the xmlrpclib module currently does not marshal instances of such
93 subclasses.
94
95 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
96 will be automatically escaped. However, it's the caller's responsibility to
97 ensure that the string is free of characters that aren't allowed in XML, such as
98 the control characters with ASCII values between 0 and 31 (except, of course,
99 tab, newline and carriage return); failing to do this will result in an XML-RPC
100 request that isn't well-formed XML. If you have to pass arbitrary strings via
101 XML-RPC, use the :class:`Binary` wrapper class described below.
102
103 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
104 compatibility. New code should use :class:`ServerProxy`.
105
106 .. versionchanged:: 2.5
107 The *use_datetime* flag was added.
108
109 .. versionchanged:: 2.6
Georg Brandla7395032007-10-21 12:15:05 +0000110 Instances of :term:`new-style class`\es can be passed in if they have an
111 *__dict__* attribute and don't have a base class that is marshalled in a
112 special way.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
114
115.. seealso::
116
117 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Andrew M. Kuchlingde680372008-01-11 19:33:24 +0000118 A good description of XML-RPC operation and client software in several languages.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119 Contains pretty much everything an XML-RPC client developer needs to know.
120
Andrew M. Kuchlingde680372008-01-11 19:33:24 +0000121 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
122 Describes the XML-RPC protocol extension for introspection.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000123
124
125.. _serverproxy-objects:
126
127ServerProxy Objects
128-------------------
129
130A :class:`ServerProxy` instance has a method corresponding to each remote
131procedure call accepted by the XML-RPC server. Calling the method performs an
132RPC, dispatched by both name and argument signature (e.g. the same method name
133can be overloaded with multiple argument signatures). The RPC finishes by
134returning a value, which may be either returned data in a conformant type or a
135:class:`Fault` or :class:`ProtocolError` object indicating an error.
136
137Servers that support the XML introspection API support some common methods
138grouped under the reserved :attr:`system` member:
139
140
141.. method:: ServerProxy.system.listMethods()
142
143 This method returns a list of strings, one for each (non-system) method
144 supported by the XML-RPC server.
145
146
147.. method:: ServerProxy.system.methodSignature(name)
148
149 This method takes one parameter, the name of a method implemented by the XML-RPC
150 server.It returns an array of possible signatures for this method. A signature
151 is an array of types. The first of these types is the return type of the method,
152 the rest are parameters.
153
154 Because multiple signatures (ie. overloading) is permitted, this method returns
155 a list of signatures rather than a singleton.
156
157 Signatures themselves are restricted to the top level parameters expected by a
158 method. For instance if a method expects one array of structs as a parameter,
159 and it returns a string, its signature is simply "string, array". If it expects
160 three integers and returns a string, its signature is "string, int, int, int".
161
162 If no signature is defined for the method, a non-array value is returned. In
163 Python this means that the type of the returned value will be something other
164 that list.
165
166
167.. method:: ServerProxy.system.methodHelp(name)
168
169 This method takes one parameter, the name of a method implemented by the XML-RPC
170 server. It returns a documentation string describing the use of that method. If
171 no such string is available, an empty string is returned. The documentation
172 string may contain HTML markup.
173
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
175.. _boolean-objects:
176
177Boolean Objects
178---------------
179
180This class may be initialized from any Python value; the instance returned
181depends only on its truth value. It supports various Python operators through
182:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
183methods, all implemented in the obvious ways.
184
185It also has the following method, supported mainly for internal use by the
186unmarshalling code:
187
188
189.. method:: Boolean.encode(out)
190
191 Write the XML-RPC encoding of this Boolean item to the out stream object.
192
Georg Brandl0a0cf162007-12-03 20:03:46 +0000193A working example follows. The server code::
194
195 import xmlrpclib
196 from SimpleXMLRPCServer import SimpleXMLRPCServer
197
198 def is_even(n):
199 return n%2 == 0
200
201 server = SimpleXMLRPCServer(("localhost", 8000))
202 print "Listening on port 8000..."
203 server.register_function(is_even, "is_even")
204 server.serve_forever()
205
206The client code for the preceding server::
207
208 import xmlrpclib
209
210 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
211 print "3 is even: %s" % str(proxy.is_even(3))
212 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000213
214.. _datetime-objects:
215
216DateTime Objects
217----------------
218
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000219This class may be initialized with seconds since the epoch, a time
220tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
221instance. It has the following methods, supported mainly for internal
222use by the marshalling/unmarshalling code:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
224
225.. method:: DateTime.decode(string)
226
227 Accept a string as the instance's new time value.
228
229
230.. method:: DateTime.encode(out)
231
232 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
233 object.
234
235It also supports certain of Python's built-in operators through :meth:`__cmp__`
236and :meth:`__repr__` methods.
237
Georg Brandl0a0cf162007-12-03 20:03:46 +0000238A working example follows. The server code::
239
240 import datetime
241 from SimpleXMLRPCServer import SimpleXMLRPCServer
242 import xmlrpclib
243
244 def today():
245 today = datetime.datetime.today()
246 return xmlrpclib.DateTime(today)
247
248 server = SimpleXMLRPCServer(("localhost", 8000))
249 print "Listening on port 8000..."
250 server.register_function(today, "today")
251 server.serve_forever()
252
253The client code for the preceding server::
254
255 import xmlrpclib
256 import datetime
257
258 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
259
260 today = proxy.today()
261 # convert the ISO8601 string to a datetime object
262 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
263 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264
265.. _binary-objects:
266
267Binary Objects
268--------------
269
270This class may be initialized from string data (which may include NULs). The
271primary access to the content of a :class:`Binary` object is provided by an
272attribute:
273
274
275.. attribute:: Binary.data
276
277 The binary data encapsulated by the :class:`Binary` instance. The data is
278 provided as an 8-bit string.
279
280:class:`Binary` objects have the following methods, supported mainly for
281internal use by the marshalling/unmarshalling code:
282
283
284.. method:: Binary.decode(string)
285
286 Accept a base64 string and decode it as the instance's new data.
287
288
289.. method:: Binary.encode(out)
290
291 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
292
293It also supports certain of Python's built-in operators through a
294:meth:`__cmp__` method.
295
Georg Brandl0a0cf162007-12-03 20:03:46 +0000296Example usage of the binary objects. We're going to transfer an image over
297XMLRPC::
298
299 from SimpleXMLRPCServer import SimpleXMLRPCServer
300 import xmlrpclib
301
302 def python_logo():
303 handle = open("python_logo.jpg")
304 return xmlrpclib.Binary(handle.read())
305 handle.close()
306
307 server = SimpleXMLRPCServer(("localhost", 8000))
308 print "Listening on port 8000..."
309 server.register_function(python_logo, 'python_logo')
310
311 server.serve_forever()
312
313The client gets the image and saves it to a file::
314
315 import xmlrpclib
316
317 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
318 handle = open("fetched_python_logo.jpg", "w")
319 handle.write(proxy.python_logo().data)
320 handle.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000321
322.. _fault-objects:
323
324Fault Objects
325-------------
326
327A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
328objects have the following members:
329
330
331.. attribute:: Fault.faultCode
332
333 A string indicating the fault type.
334
335
336.. attribute:: Fault.faultString
337
338 A string containing a diagnostic message associated with the fault.
339
Georg Brandl0a0cf162007-12-03 20:03:46 +0000340In the following example we're going to intentionally cause a :exc:`Fault` by
341returning a complex type object. The server code::
342
343 from SimpleXMLRPCServer import SimpleXMLRPCServer
344
345 # A marshalling error is going to occur because we're returning a
346 # complex number
347 def add(x,y):
348 return x+y+0j
349
350 server = SimpleXMLRPCServer(("localhost", 8000))
351 print "Listening on port 8000..."
352 server.register_function(add, 'add')
353
354 server.serve_forever()
355
356The client code for the preceding server::
357
358 import xmlrpclib
359
360 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
361 try:
362 proxy.add(2, 5)
363 except xmlrpclib.Fault, err:
364 print "A fault occured"
365 print "Fault code: %d" % err.faultCode
366 print "Fault string: %s" % err.faultString
367
368
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
370.. _protocol-error-objects:
371
372ProtocolError Objects
373---------------------
374
375A :class:`ProtocolError` object describes a protocol error in the underlying
376transport layer (such as a 404 'not found' error if the server named by the URI
377does not exist). It has the following members:
378
379
380.. attribute:: ProtocolError.url
381
382 The URI or URL that triggered the error.
383
384
385.. attribute:: ProtocolError.errcode
386
387 The error code.
388
389
390.. attribute:: ProtocolError.errmsg
391
392 The error message or diagnostic string.
393
394
395.. attribute:: ProtocolError.headers
396
397 A string containing the headers of the HTTP/HTTPS request that triggered the
398 error.
399
Georg Brandl0a0cf162007-12-03 20:03:46 +0000400In the following example we're going to intentionally cause a :exc:`ProtocolError`
401by providing an invalid URI::
402
403 import xmlrpclib
404
405 # create a ServerProxy with an invalid URI
406 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
407
408 try:
409 proxy.some_method()
410 except xmlrpclib.ProtocolError, err:
411 print "A protocol error occured"
412 print "URL: %s" % err.url
413 print "HTTP/HTTPS headers: %s" % err.headers
414 print "Error code: %d" % err.errcode
415 print "Error message: %s" % err.errmsg
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416
417MultiCall Objects
418-----------------
419
420.. versionadded:: 2.4
421
422In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
423encapsulate multiple calls to a remote server into a single request.
424
425
426.. class:: MultiCall(server)
427
428 Create an object used to boxcar method calls. *server* is the eventual target of
429 the call. Calls can be made to the result object, but they will immediately
430 return ``None``, and only store the call name and parameters in the
431 :class:`MultiCall` object. Calling the object itself causes all stored calls to
432 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000433 is a :term:`generator`; iterating over this generator yields the individual
434 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
Georg Brandl0a0cf162007-12-03 20:03:46 +0000436A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000437
Georg Brandl0a0cf162007-12-03 20:03:46 +0000438 from SimpleXMLRPCServer import SimpleXMLRPCServer
439
440 def add(x,y):
441 return x+y
442
443 def subtract(x, y):
444 return x-y
445
446 def multiply(x, y):
447 return x*y
448
449 def divide(x, y):
450 return x/y
451
452 # A simple server with simple arithmetic functions
453 server = SimpleXMLRPCServer(("localhost", 8000))
454 print "Listening on port 8000..."
455 server.register_multicall_functions()
456 server.register_function(add, 'add')
457 server.register_function(subtract, 'subtract')
458 server.register_function(multiply, 'multiply')
459 server.register_function(divide, 'divide')
460 server.serve_forever()
461
462The client code for the preceding server::
463
464 import xmlrpclib
465
466 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
467 multicall = xmlrpclib.MultiCall(proxy)
468 multicall.add(7,3)
469 multicall.subtract(7,3)
470 multicall.multiply(7,3)
471 multicall.divide(7,3)
472 result = multicall()
473
474 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000475
476
477Convenience Functions
478---------------------
479
480
481.. function:: boolean(value)
482
483 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
484 ``False``.
485
486
487.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
488
489 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
490 is true. *params* can be either a tuple of arguments or an instance of the
491 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
492 can be returned, meaning that *params* must be of length 1. *encoding*, if
493 supplied, is the encoding to use in the generated XML; the default is UTF-8.
494 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
495 it via an extension, provide a true value for *allow_none*.
496
497
498.. function:: loads(data[, use_datetime])
499
500 Convert an XML-RPC request or response into Python objects, a ``(params,
501 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
502 ``None`` if no method name is present in the packet. If the XML-RPC packet
503 represents a fault condition, this function will raise a :exc:`Fault` exception.
504 The *use_datetime* flag can be used to cause date/time values to be presented as
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000505 :class:`datetime.datetime` objects; this is false by default.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
507 .. versionchanged:: 2.5
508 The *use_datetime* flag was added.
509
510
511.. _xmlrpc-client-example:
512
513Example of Client Usage
514-----------------------
515
516::
517
518 # simple test program (from the XML-RPC specification)
519 from xmlrpclib import ServerProxy, Error
520
521 # server = ServerProxy("http://localhost:8000") # local server
522 server = ServerProxy("http://betty.userland.com")
523
524 print server
525
526 try:
527 print server.examples.getStateName(41)
528 except Error, v:
529 print "ERROR", v
530
531To access an XML-RPC server through a proxy, you need to define a custom
Georg Brandlb19be572007-12-29 10:57:00 +0000532transport. The following example shows how:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000533
Georg Brandlb19be572007-12-29 10:57:00 +0000534.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl8ec7f652007-08-15 14:28:01 +0000535
536::
537
538 import xmlrpclib, httplib
539
540 class ProxiedTransport(xmlrpclib.Transport):
541 def set_proxy(self, proxy):
542 self.proxy = proxy
543 def make_connection(self, host):
544 self.realhost = host
545 h = httplib.HTTP(self.proxy)
546 return h
547 def send_request(self, connection, handler, request_body):
548 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
549 def send_host(self, connection, host):
550 connection.putheader('Host', self.realhost)
551
552 p = ProxiedTransport()
553 p.set_proxy('proxy-server:8080')
554 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
555 print server.currentTime.getCurrentTime()
556
Georg Brandl0a0cf162007-12-03 20:03:46 +0000557
558Example of Client and Server Usage
559----------------------------------
560
561See :ref:`simplexmlrpcserver-example`.
562
563