blob: 51d97a23fa33ceeeb1b839eb3723265bfe792837 [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
Skip Montanaro6d9aafa2008-04-22 22:45:09 +0000124 `XML-RPC Specification <http://www.xmlrpc.com/spec>`_
125 The official specification.
126
127 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
128 Fredrik Lundh's "unofficial errata, intended to clarify certain
129 details in the XML-RPC specification, as well as hint at
130 'best practices' to use when designing your own XML-RPC
131 implementations."
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
133.. _serverproxy-objects:
134
135ServerProxy Objects
136-------------------
137
138A :class:`ServerProxy` instance has a method corresponding to each remote
139procedure call accepted by the XML-RPC server. Calling the method performs an
140RPC, dispatched by both name and argument signature (e.g. the same method name
141can be overloaded with multiple argument signatures). The RPC finishes by
142returning a value, which may be either returned data in a conformant type or a
143:class:`Fault` or :class:`ProtocolError` object indicating an error.
144
145Servers that support the XML introspection API support some common methods
146grouped under the reserved :attr:`system` member:
147
148
149.. method:: ServerProxy.system.listMethods()
150
151 This method returns a list of strings, one for each (non-system) method
152 supported by the XML-RPC server.
153
154
155.. method:: ServerProxy.system.methodSignature(name)
156
157 This method takes one parameter, the name of a method implemented by the XML-RPC
158 server.It returns an array of possible signatures for this method. A signature
159 is an array of types. The first of these types is the return type of the method,
160 the rest are parameters.
161
162 Because multiple signatures (ie. overloading) is permitted, this method returns
163 a list of signatures rather than a singleton.
164
165 Signatures themselves are restricted to the top level parameters expected by a
166 method. For instance if a method expects one array of structs as a parameter,
167 and it returns a string, its signature is simply "string, array". If it expects
168 three integers and returns a string, its signature is "string, int, int, int".
169
170 If no signature is defined for the method, a non-array value is returned. In
171 Python this means that the type of the returned value will be something other
172 that list.
173
174
175.. method:: ServerProxy.system.methodHelp(name)
176
177 This method takes one parameter, the name of a method implemented by the XML-RPC
178 server. It returns a documentation string describing the use of that method. If
179 no such string is available, an empty string is returned. The documentation
180 string may contain HTML markup.
181
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183.. _boolean-objects:
184
185Boolean Objects
186---------------
187
188This class may be initialized from any Python value; the instance returned
189depends only on its truth value. It supports various Python operators through
190:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
191methods, all implemented in the obvious ways.
192
193It also has the following method, supported mainly for internal use by the
194unmarshalling code:
195
196
197.. method:: Boolean.encode(out)
198
199 Write the XML-RPC encoding of this Boolean item to the out stream object.
200
Georg Brandl0a0cf162007-12-03 20:03:46 +0000201A working example follows. The server code::
202
203 import xmlrpclib
204 from SimpleXMLRPCServer import SimpleXMLRPCServer
205
206 def is_even(n):
207 return n%2 == 0
208
209 server = SimpleXMLRPCServer(("localhost", 8000))
210 print "Listening on port 8000..."
211 server.register_function(is_even, "is_even")
212 server.serve_forever()
213
214The client code for the preceding server::
215
216 import xmlrpclib
217
218 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
219 print "3 is even: %s" % str(proxy.is_even(3))
220 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221
222.. _datetime-objects:
223
224DateTime Objects
225----------------
226
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000227This class may be initialized with seconds since the epoch, a time
228tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
229instance. It has the following methods, supported mainly for internal
230use by the marshalling/unmarshalling code:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000231
232
233.. method:: DateTime.decode(string)
234
235 Accept a string as the instance's new time value.
236
237
238.. method:: DateTime.encode(out)
239
240 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
241 object.
242
243It also supports certain of Python's built-in operators through :meth:`__cmp__`
244and :meth:`__repr__` methods.
245
Georg Brandl0a0cf162007-12-03 20:03:46 +0000246A working example follows. The server code::
247
248 import datetime
249 from SimpleXMLRPCServer import SimpleXMLRPCServer
250 import xmlrpclib
251
252 def today():
253 today = datetime.datetime.today()
254 return xmlrpclib.DateTime(today)
255
256 server = SimpleXMLRPCServer(("localhost", 8000))
257 print "Listening on port 8000..."
258 server.register_function(today, "today")
259 server.serve_forever()
260
261The client code for the preceding server::
262
263 import xmlrpclib
264 import datetime
265
266 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
267
268 today = proxy.today()
269 # convert the ISO8601 string to a datetime object
270 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
271 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272
273.. _binary-objects:
274
275Binary Objects
276--------------
277
278This class may be initialized from string data (which may include NULs). The
279primary access to the content of a :class:`Binary` object is provided by an
280attribute:
281
282
283.. attribute:: Binary.data
284
285 The binary data encapsulated by the :class:`Binary` instance. The data is
286 provided as an 8-bit string.
287
288:class:`Binary` objects have the following methods, supported mainly for
289internal use by the marshalling/unmarshalling code:
290
291
292.. method:: Binary.decode(string)
293
294 Accept a base64 string and decode it as the instance's new data.
295
296
297.. method:: Binary.encode(out)
298
299 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
300
Skip Montanaro6d9aafa2008-04-22 22:45:09 +0000301 The encoded data will have newlines every 76 characters as per
302 `RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
303 which was the de facto standard base64 specification when the
304 XML-RPC spec was written.
305
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306It also supports certain of Python's built-in operators through a
307:meth:`__cmp__` method.
308
Georg Brandl0a0cf162007-12-03 20:03:46 +0000309Example usage of the binary objects. We're going to transfer an image over
310XMLRPC::
311
312 from SimpleXMLRPCServer import SimpleXMLRPCServer
313 import xmlrpclib
314
315 def python_logo():
316 handle = open("python_logo.jpg")
317 return xmlrpclib.Binary(handle.read())
318 handle.close()
319
320 server = SimpleXMLRPCServer(("localhost", 8000))
321 print "Listening on port 8000..."
322 server.register_function(python_logo, 'python_logo')
323
324 server.serve_forever()
325
326The client gets the image and saves it to a file::
327
328 import xmlrpclib
329
330 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
331 handle = open("fetched_python_logo.jpg", "w")
332 handle.write(proxy.python_logo().data)
333 handle.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334
335.. _fault-objects:
336
337Fault Objects
338-------------
339
340A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
341objects have the following members:
342
343
344.. attribute:: Fault.faultCode
345
346 A string indicating the fault type.
347
348
349.. attribute:: Fault.faultString
350
351 A string containing a diagnostic message associated with the fault.
352
Georg Brandl0a0cf162007-12-03 20:03:46 +0000353In the following example we're going to intentionally cause a :exc:`Fault` by
354returning a complex type object. The server code::
355
356 from SimpleXMLRPCServer import SimpleXMLRPCServer
357
358 # A marshalling error is going to occur because we're returning a
359 # complex number
360 def add(x,y):
361 return x+y+0j
362
363 server = SimpleXMLRPCServer(("localhost", 8000))
364 print "Listening on port 8000..."
365 server.register_function(add, 'add')
366
367 server.serve_forever()
368
369The client code for the preceding server::
370
371 import xmlrpclib
372
373 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
374 try:
375 proxy.add(2, 5)
376 except xmlrpclib.Fault, err:
377 print "A fault occured"
378 print "Fault code: %d" % err.faultCode
379 print "Fault string: %s" % err.faultString
380
381
Georg Brandl8ec7f652007-08-15 14:28:01 +0000382
383.. _protocol-error-objects:
384
385ProtocolError Objects
386---------------------
387
388A :class:`ProtocolError` object describes a protocol error in the underlying
389transport layer (such as a 404 'not found' error if the server named by the URI
390does not exist). It has the following members:
391
392
393.. attribute:: ProtocolError.url
394
395 The URI or URL that triggered the error.
396
397
398.. attribute:: ProtocolError.errcode
399
400 The error code.
401
402
403.. attribute:: ProtocolError.errmsg
404
405 The error message or diagnostic string.
406
407
408.. attribute:: ProtocolError.headers
409
410 A string containing the headers of the HTTP/HTTPS request that triggered the
411 error.
412
Georg Brandl0a0cf162007-12-03 20:03:46 +0000413In the following example we're going to intentionally cause a :exc:`ProtocolError`
414by providing an invalid URI::
415
416 import xmlrpclib
417
418 # create a ServerProxy with an invalid URI
419 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
420
421 try:
422 proxy.some_method()
423 except xmlrpclib.ProtocolError, err:
424 print "A protocol error occured"
425 print "URL: %s" % err.url
426 print "HTTP/HTTPS headers: %s" % err.headers
427 print "Error code: %d" % err.errcode
428 print "Error message: %s" % err.errmsg
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
430MultiCall Objects
431-----------------
432
433.. versionadded:: 2.4
434
435In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
436encapsulate multiple calls to a remote server into a single request.
437
438
439.. class:: MultiCall(server)
440
441 Create an object used to boxcar method calls. *server* is the eventual target of
442 the call. Calls can be made to the result object, but they will immediately
443 return ``None``, and only store the call name and parameters in the
444 :class:`MultiCall` object. Calling the object itself causes all stored calls to
445 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000446 is a :term:`generator`; iterating over this generator yields the individual
447 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000448
Georg Brandl0a0cf162007-12-03 20:03:46 +0000449A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000450
Georg Brandl0a0cf162007-12-03 20:03:46 +0000451 from SimpleXMLRPCServer import SimpleXMLRPCServer
452
453 def add(x,y):
454 return x+y
455
456 def subtract(x, y):
457 return x-y
458
459 def multiply(x, y):
460 return x*y
461
462 def divide(x, y):
463 return x/y
464
465 # A simple server with simple arithmetic functions
466 server = SimpleXMLRPCServer(("localhost", 8000))
467 print "Listening on port 8000..."
468 server.register_multicall_functions()
469 server.register_function(add, 'add')
470 server.register_function(subtract, 'subtract')
471 server.register_function(multiply, 'multiply')
472 server.register_function(divide, 'divide')
473 server.serve_forever()
474
475The client code for the preceding server::
476
477 import xmlrpclib
478
479 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
480 multicall = xmlrpclib.MultiCall(proxy)
481 multicall.add(7,3)
482 multicall.subtract(7,3)
483 multicall.multiply(7,3)
484 multicall.divide(7,3)
485 result = multicall()
486
487 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000488
489
490Convenience Functions
491---------------------
492
493
494.. function:: boolean(value)
495
496 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
497 ``False``.
498
499
500.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
501
502 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
503 is true. *params* can be either a tuple of arguments or an instance of the
504 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
505 can be returned, meaning that *params* must be of length 1. *encoding*, if
506 supplied, is the encoding to use in the generated XML; the default is UTF-8.
507 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
508 it via an extension, provide a true value for *allow_none*.
509
510
511.. function:: loads(data[, use_datetime])
512
513 Convert an XML-RPC request or response into Python objects, a ``(params,
514 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
515 ``None`` if no method name is present in the packet. If the XML-RPC packet
516 represents a fault condition, this function will raise a :exc:`Fault` exception.
517 The *use_datetime* flag can be used to cause date/time values to be presented as
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000518 :class:`datetime.datetime` objects; this is false by default.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000519
520 .. versionchanged:: 2.5
521 The *use_datetime* flag was added.
522
523
524.. _xmlrpc-client-example:
525
526Example of Client Usage
527-----------------------
528
529::
530
531 # simple test program (from the XML-RPC specification)
532 from xmlrpclib import ServerProxy, Error
533
534 # server = ServerProxy("http://localhost:8000") # local server
535 server = ServerProxy("http://betty.userland.com")
536
537 print server
538
539 try:
540 print server.examples.getStateName(41)
541 except Error, v:
542 print "ERROR", v
543
544To access an XML-RPC server through a proxy, you need to define a custom
Georg Brandlb19be572007-12-29 10:57:00 +0000545transport. The following example shows how:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
Georg Brandlb19be572007-12-29 10:57:00 +0000547.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl8ec7f652007-08-15 14:28:01 +0000548
549::
550
551 import xmlrpclib, httplib
552
553 class ProxiedTransport(xmlrpclib.Transport):
554 def set_proxy(self, proxy):
555 self.proxy = proxy
556 def make_connection(self, host):
557 self.realhost = host
558 h = httplib.HTTP(self.proxy)
559 return h
560 def send_request(self, connection, handler, request_body):
561 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
562 def send_host(self, connection, host):
563 connection.putheader('Host', self.realhost)
564
565 p = ProxiedTransport()
566 p.set_proxy('proxy-server:8080')
567 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
568 print server.currentTime.getCurrentTime()
569
Georg Brandl0a0cf162007-12-03 20:03:46 +0000570
571Example of Client and Server Usage
572----------------------------------
573
574See :ref:`simplexmlrpcserver-example`.
575
576