blob: 4322fd0cbba8d2c2a460f24dcddd307286ea71f5 [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
Georg Brandl0a0cf162007-12-03 20:03:46 +0000205A working example follows. The server code::
206
207 import xmlrpclib
208 from SimpleXMLRPCServer import SimpleXMLRPCServer
209
210 def is_even(n):
211 return n%2 == 0
212
213 server = SimpleXMLRPCServer(("localhost", 8000))
214 print "Listening on port 8000..."
215 server.register_function(is_even, "is_even")
216 server.serve_forever()
217
218The client code for the preceding server::
219
220 import xmlrpclib
221
222 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
223 print "3 is even: %s" % str(proxy.is_even(3))
224 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
226.. _datetime-objects:
227
228DateTime Objects
229----------------
230
231This class may be initialized with seconds since the epoch, a time tuple, an ISO
2328601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
233or :class:`datetime.time` instance. It has the following methods, supported
234mainly for internal use by the marshalling/unmarshalling code:
235
236
237.. method:: DateTime.decode(string)
238
239 Accept a string as the instance's new time value.
240
241
242.. method:: DateTime.encode(out)
243
244 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
245 object.
246
247It also supports certain of Python's built-in operators through :meth:`__cmp__`
248and :meth:`__repr__` methods.
249
Georg Brandl0a0cf162007-12-03 20:03:46 +0000250A working example follows. The server code::
251
252 import datetime
253 from SimpleXMLRPCServer import SimpleXMLRPCServer
254 import xmlrpclib
255
256 def today():
257 today = datetime.datetime.today()
258 return xmlrpclib.DateTime(today)
259
260 server = SimpleXMLRPCServer(("localhost", 8000))
261 print "Listening on port 8000..."
262 server.register_function(today, "today")
263 server.serve_forever()
264
265The client code for the preceding server::
266
267 import xmlrpclib
268 import datetime
269
270 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
271
272 today = proxy.today()
273 # convert the ISO8601 string to a datetime object
274 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
275 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
277.. _binary-objects:
278
279Binary Objects
280--------------
281
282This class may be initialized from string data (which may include NULs). The
283primary access to the content of a :class:`Binary` object is provided by an
284attribute:
285
286
287.. attribute:: Binary.data
288
289 The binary data encapsulated by the :class:`Binary` instance. The data is
290 provided as an 8-bit string.
291
292:class:`Binary` objects have the following methods, supported mainly for
293internal use by the marshalling/unmarshalling code:
294
295
296.. method:: Binary.decode(string)
297
298 Accept a base64 string and decode it as the instance's new data.
299
300
301.. method:: Binary.encode(out)
302
303 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
304
305It also supports certain of Python's built-in operators through a
306:meth:`__cmp__` method.
307
Georg Brandl0a0cf162007-12-03 20:03:46 +0000308Example usage of the binary objects. We're going to transfer an image over
309XMLRPC::
310
311 from SimpleXMLRPCServer import SimpleXMLRPCServer
312 import xmlrpclib
313
314 def python_logo():
315 handle = open("python_logo.jpg")
316 return xmlrpclib.Binary(handle.read())
317 handle.close()
318
319 server = SimpleXMLRPCServer(("localhost", 8000))
320 print "Listening on port 8000..."
321 server.register_function(python_logo, 'python_logo')
322
323 server.serve_forever()
324
325The client gets the image and saves it to a file::
326
327 import xmlrpclib
328
329 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
330 handle = open("fetched_python_logo.jpg", "w")
331 handle.write(proxy.python_logo().data)
332 handle.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000333
334.. _fault-objects:
335
336Fault Objects
337-------------
338
339A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
340objects have the following members:
341
342
343.. attribute:: Fault.faultCode
344
345 A string indicating the fault type.
346
347
348.. attribute:: Fault.faultString
349
350 A string containing a diagnostic message associated with the fault.
351
Georg Brandl0a0cf162007-12-03 20:03:46 +0000352In the following example we're going to intentionally cause a :exc:`Fault` by
353returning a complex type object. The server code::
354
355 from SimpleXMLRPCServer import SimpleXMLRPCServer
356
357 # A marshalling error is going to occur because we're returning a
358 # complex number
359 def add(x,y):
360 return x+y+0j
361
362 server = SimpleXMLRPCServer(("localhost", 8000))
363 print "Listening on port 8000..."
364 server.register_function(add, 'add')
365
366 server.serve_forever()
367
368The client code for the preceding server::
369
370 import xmlrpclib
371
372 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
373 try:
374 proxy.add(2, 5)
375 except xmlrpclib.Fault, err:
376 print "A fault occured"
377 print "Fault code: %d" % err.faultCode
378 print "Fault string: %s" % err.faultString
379
380
Georg Brandl8ec7f652007-08-15 14:28:01 +0000381
382.. _protocol-error-objects:
383
384ProtocolError Objects
385---------------------
386
387A :class:`ProtocolError` object describes a protocol error in the underlying
388transport layer (such as a 404 'not found' error if the server named by the URI
389does not exist). It has the following members:
390
391
392.. attribute:: ProtocolError.url
393
394 The URI or URL that triggered the error.
395
396
397.. attribute:: ProtocolError.errcode
398
399 The error code.
400
401
402.. attribute:: ProtocolError.errmsg
403
404 The error message or diagnostic string.
405
406
407.. attribute:: ProtocolError.headers
408
409 A string containing the headers of the HTTP/HTTPS request that triggered the
410 error.
411
Georg Brandl0a0cf162007-12-03 20:03:46 +0000412In the following example we're going to intentionally cause a :exc:`ProtocolError`
413by providing an invalid URI::
414
415 import xmlrpclib
416
417 # create a ServerProxy with an invalid URI
418 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
419
420 try:
421 proxy.some_method()
422 except xmlrpclib.ProtocolError, err:
423 print "A protocol error occured"
424 print "URL: %s" % err.url
425 print "HTTP/HTTPS headers: %s" % err.headers
426 print "Error code: %d" % err.errcode
427 print "Error message: %s" % err.errmsg
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428
429MultiCall Objects
430-----------------
431
432.. versionadded:: 2.4
433
434In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
435encapsulate multiple calls to a remote server into a single request.
436
437
438.. class:: MultiCall(server)
439
440 Create an object used to boxcar method calls. *server* is the eventual target of
441 the call. Calls can be made to the result object, but they will immediately
442 return ``None``, and only store the call name and parameters in the
443 :class:`MultiCall` object. Calling the object itself causes all stored calls to
444 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000445 is a :term:`generator`; iterating over this generator yields the individual
446 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000447
Georg Brandl0a0cf162007-12-03 20:03:46 +0000448A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000449
Georg Brandl0a0cf162007-12-03 20:03:46 +0000450 from SimpleXMLRPCServer import SimpleXMLRPCServer
451
452 def add(x,y):
453 return x+y
454
455 def subtract(x, y):
456 return x-y
457
458 def multiply(x, y):
459 return x*y
460
461 def divide(x, y):
462 return x/y
463
464 # A simple server with simple arithmetic functions
465 server = SimpleXMLRPCServer(("localhost", 8000))
466 print "Listening on port 8000..."
467 server.register_multicall_functions()
468 server.register_function(add, 'add')
469 server.register_function(subtract, 'subtract')
470 server.register_function(multiply, 'multiply')
471 server.register_function(divide, 'divide')
472 server.serve_forever()
473
474The client code for the preceding server::
475
476 import xmlrpclib
477
478 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
479 multicall = xmlrpclib.MultiCall(proxy)
480 multicall.add(7,3)
481 multicall.subtract(7,3)
482 multicall.multiply(7,3)
483 multicall.divide(7,3)
484 result = multicall()
485
486 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000487
488
489Convenience Functions
490---------------------
491
492
493.. function:: boolean(value)
494
495 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
496 ``False``.
497
498
499.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
500
501 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
502 is true. *params* can be either a tuple of arguments or an instance of the
503 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
504 can be returned, meaning that *params* must be of length 1. *encoding*, if
505 supplied, is the encoding to use in the generated XML; the default is UTF-8.
506 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
507 it via an extension, provide a true value for *allow_none*.
508
509
510.. function:: loads(data[, use_datetime])
511
512 Convert an XML-RPC request or response into Python objects, a ``(params,
513 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
514 ``None`` if no method name is present in the packet. If the XML-RPC packet
515 represents a fault condition, this function will raise a :exc:`Fault` exception.
516 The *use_datetime* flag can be used to cause date/time values to be presented as
517 :class:`datetime.datetime` objects; this is false by default. Note that even if
518 you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
519 objects, they are converted to :class:`DateTime` objects internally, so only
520 :class:`datetime.datetime` objects will be returned.
521
522 .. versionchanged:: 2.5
523 The *use_datetime* flag was added.
524
525
526.. _xmlrpc-client-example:
527
528Example of Client Usage
529-----------------------
530
531::
532
533 # simple test program (from the XML-RPC specification)
534 from xmlrpclib import ServerProxy, Error
535
536 # server = ServerProxy("http://localhost:8000") # local server
537 server = ServerProxy("http://betty.userland.com")
538
539 print server
540
541 try:
542 print server.examples.getStateName(41)
543 except Error, v:
544 print "ERROR", v
545
546To access an XML-RPC server through a proxy, you need to define a custom
547transport. The following example, written by NoboNobo, shows how:
548
549.. % fill in original author's name if we ever learn it
550
551.. % Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
552
553::
554
555 import xmlrpclib, httplib
556
557 class ProxiedTransport(xmlrpclib.Transport):
558 def set_proxy(self, proxy):
559 self.proxy = proxy
560 def make_connection(self, host):
561 self.realhost = host
562 h = httplib.HTTP(self.proxy)
563 return h
564 def send_request(self, connection, handler, request_body):
565 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
566 def send_host(self, connection, host):
567 connection.putheader('Host', self.realhost)
568
569 p = ProxiedTransport()
570 p.set_proxy('proxy-server:8080')
571 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
572 print server.currentTime.getCurrentTime()
573
Georg Brandl0a0cf162007-12-03 20:03:46 +0000574
575Example of Client and Server Usage
576----------------------------------
577
578See :ref:`simplexmlrpcserver-example`.
579
580