blob: a0cbff9d55e013d72f5a26cf7eb10d0690661719 [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.
37 :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time`
38 objects may be passed to calls. :class:`datetime.date` objects are converted
39 with a time of "00:00:00". :class:`datetime.time` objects are converted using
40 today's date.
41
42 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
43 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
44 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
45 the remote server as part of the connection process when invoking an XML-RPC
46 method. You only need to use this if the remote server requires a Basic
47 Authentication user and password.
48
49 The returned instance is a proxy object with methods that can be used to invoke
50 corresponding RPC calls on the remote server. If the remote server supports the
51 introspection API, the proxy can also be used to query the remote server for the
52 methods it supports (service discovery) and fetch other server-associated
53 metadata.
54
55 :class:`ServerProxy` instance methods take Python basic types and objects as
56 arguments and return Python basic types and classes. Types that are conformable
57 (e.g. that can be marshalled through XML), include the following (and except
58 where noted, they are unmarshalled as the same Python type):
59
60 +---------------------------------+---------------------------------------------+
61 | Name | Meaning |
62 +=================================+=============================================+
63 | :const:`boolean` | The :const:`True` and :const:`False` |
64 | | constants |
65 +---------------------------------+---------------------------------------------+
66 | :const:`integers` | Pass in directly |
67 +---------------------------------+---------------------------------------------+
68 | :const:`floating-point numbers` | Pass in directly |
69 +---------------------------------+---------------------------------------------+
70 | :const:`strings` | Pass in directly |
71 +---------------------------------+---------------------------------------------+
72 | :const:`arrays` | Any Python sequence type containing |
73 | | conformable elements. Arrays are returned |
74 | | as lists |
75 +---------------------------------+---------------------------------------------+
76 | :const:`structures` | A Python dictionary. Keys must be strings, |
77 | | values may be any conformable type. Objects |
78 | | of user-defined classes can be passed in; |
79 | | only their *__dict__* attribute is |
80 | | transmitted. |
81 +---------------------------------+---------------------------------------------+
82 | :const:`dates` | in seconds since the epoch (pass in an |
83 | | instance of the :class:`DateTime` class) or |
84 | | a :class:`datetime.datetime`, |
85 | | :class:`datetime.date` or |
86 | | :class:`datetime.time` instance |
87 +---------------------------------+---------------------------------------------+
88 | :const:`binary data` | pass in an instance of the :class:`Binary` |
89 | | wrapper class |
90 +---------------------------------+---------------------------------------------+
91
92 This is the full set of data types supported by XML-RPC. Method calls may also
93 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
94 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
95 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
96 :exc:`Error`. Note that even though starting with Python 2.2 you can subclass
97 builtin types, the xmlrpclib module currently does not marshal instances of such
98 subclasses.
99
100 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
101 will be automatically escaped. However, it's the caller's responsibility to
102 ensure that the string is free of characters that aren't allowed in XML, such as
103 the control characters with ASCII values between 0 and 31 (except, of course,
104 tab, newline and carriage return); failing to do this will result in an XML-RPC
105 request that isn't well-formed XML. If you have to pass arbitrary strings via
106 XML-RPC, use the :class:`Binary` wrapper class described below.
107
108 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
109 compatibility. New code should use :class:`ServerProxy`.
110
111 .. versionchanged:: 2.5
112 The *use_datetime* flag was added.
113
114 .. versionchanged:: 2.6
Georg Brandla7395032007-10-21 12:15:05 +0000115 Instances of :term:`new-style class`\es can be passed in if they have an
116 *__dict__* attribute and don't have a base class that is marshalled in a
117 special way.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118
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:`__nonzero__`
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
Georg Brandl0a0cf162007-12-03 20:03:46 +0000204A working example follows. The server code::
205
206 import xmlrpclib
207 from SimpleXMLRPCServer import SimpleXMLRPCServer
208
209 def is_even(n):
210 return n%2 == 0
211
212 server = SimpleXMLRPCServer(("localhost", 8000))
213 print "Listening on port 8000..."
214 server.register_function(is_even, "is_even")
215 server.serve_forever()
216
217The client code for the preceding server::
218
219 import xmlrpclib
220
221 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
222 print "3 is even: %s" % str(proxy.is_even(3))
223 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224
225.. _datetime-objects:
226
227DateTime Objects
228----------------
229
230This class may be initialized with seconds since the epoch, a time tuple, an ISO
2318601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date`
232or :class:`datetime.time` instance. It has the following methods, supported
233mainly for internal use by the marshalling/unmarshalling code:
234
235
236.. method:: DateTime.decode(string)
237
238 Accept a string as the instance's new time value.
239
240
241.. method:: DateTime.encode(out)
242
243 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
244 object.
245
246It also supports certain of Python's built-in operators through :meth:`__cmp__`
247and :meth:`__repr__` methods.
248
Georg Brandl0a0cf162007-12-03 20:03:46 +0000249A working example follows. The server code::
250
251 import datetime
252 from SimpleXMLRPCServer import SimpleXMLRPCServer
253 import xmlrpclib
254
255 def today():
256 today = datetime.datetime.today()
257 return xmlrpclib.DateTime(today)
258
259 server = SimpleXMLRPCServer(("localhost", 8000))
260 print "Listening on port 8000..."
261 server.register_function(today, "today")
262 server.serve_forever()
263
264The client code for the preceding server::
265
266 import xmlrpclib
267 import datetime
268
269 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
270
271 today = proxy.today()
272 # convert the ISO8601 string to a datetime object
273 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
274 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
276.. _binary-objects:
277
278Binary Objects
279--------------
280
281This class may be initialized from string data (which may include NULs). The
282primary access to the content of a :class:`Binary` object is provided by an
283attribute:
284
285
286.. attribute:: Binary.data
287
288 The binary data encapsulated by the :class:`Binary` instance. The data is
289 provided as an 8-bit string.
290
291:class:`Binary` objects have the following methods, supported mainly for
292internal use by the marshalling/unmarshalling code:
293
294
295.. method:: Binary.decode(string)
296
297 Accept a base64 string and decode it as the instance's new data.
298
299
300.. method:: Binary.encode(out)
301
302 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
303
304It also supports certain of Python's built-in operators through a
305:meth:`__cmp__` method.
306
Georg Brandl0a0cf162007-12-03 20:03:46 +0000307Example usage of the binary objects. We're going to transfer an image over
308XMLRPC::
309
310 from SimpleXMLRPCServer import SimpleXMLRPCServer
311 import xmlrpclib
312
313 def python_logo():
314 handle = open("python_logo.jpg")
315 return xmlrpclib.Binary(handle.read())
316 handle.close()
317
318 server = SimpleXMLRPCServer(("localhost", 8000))
319 print "Listening on port 8000..."
320 server.register_function(python_logo, 'python_logo')
321
322 server.serve_forever()
323
324The client gets the image and saves it to a file::
325
326 import xmlrpclib
327
328 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
329 handle = open("fetched_python_logo.jpg", "w")
330 handle.write(proxy.python_logo().data)
331 handle.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
333.. _fault-objects:
334
335Fault Objects
336-------------
337
338A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
339objects have the following members:
340
341
342.. attribute:: Fault.faultCode
343
344 A string indicating the fault type.
345
346
347.. attribute:: Fault.faultString
348
349 A string containing a diagnostic message associated with the fault.
350
Georg Brandl0a0cf162007-12-03 20:03:46 +0000351In the following example we're going to intentionally cause a :exc:`Fault` by
352returning a complex type object. The server code::
353
354 from SimpleXMLRPCServer import SimpleXMLRPCServer
355
356 # A marshalling error is going to occur because we're returning a
357 # complex number
358 def add(x,y):
359 return x+y+0j
360
361 server = SimpleXMLRPCServer(("localhost", 8000))
362 print "Listening on port 8000..."
363 server.register_function(add, 'add')
364
365 server.serve_forever()
366
367The client code for the preceding server::
368
369 import xmlrpclib
370
371 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
372 try:
373 proxy.add(2, 5)
374 except xmlrpclib.Fault, err:
375 print "A fault occured"
376 print "Fault code: %d" % err.faultCode
377 print "Fault string: %s" % err.faultString
378
379
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
381.. _protocol-error-objects:
382
383ProtocolError Objects
384---------------------
385
386A :class:`ProtocolError` object describes a protocol error in the underlying
387transport layer (such as a 404 'not found' error if the server named by the URI
388does not exist). It has the following members:
389
390
391.. attribute:: ProtocolError.url
392
393 The URI or URL that triggered the error.
394
395
396.. attribute:: ProtocolError.errcode
397
398 The error code.
399
400
401.. attribute:: ProtocolError.errmsg
402
403 The error message or diagnostic string.
404
405
406.. attribute:: ProtocolError.headers
407
408 A string containing the headers of the HTTP/HTTPS request that triggered the
409 error.
410
Georg Brandl0a0cf162007-12-03 20:03:46 +0000411In the following example we're going to intentionally cause a :exc:`ProtocolError`
412by providing an invalid URI::
413
414 import xmlrpclib
415
416 # create a ServerProxy with an invalid URI
417 proxy = xmlrpclib.ServerProxy("http://invalidaddress/")
418
419 try:
420 proxy.some_method()
421 except xmlrpclib.ProtocolError, err:
422 print "A protocol error occured"
423 print "URL: %s" % err.url
424 print "HTTP/HTTPS headers: %s" % err.headers
425 print "Error code: %d" % err.errcode
426 print "Error message: %s" % err.errmsg
Georg Brandl8ec7f652007-08-15 14:28:01 +0000427
428MultiCall Objects
429-----------------
430
431.. versionadded:: 2.4
432
433In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
434encapsulate multiple calls to a remote server into a single request.
435
436
437.. class:: MultiCall(server)
438
439 Create an object used to boxcar method calls. *server* is the eventual target of
440 the call. Calls can be made to the result object, but they will immediately
441 return ``None``, and only store the call name and parameters in the
442 :class:`MultiCall` object. Calling the object itself causes all stored calls to
443 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000444 is a :term:`generator`; iterating over this generator yields the individual
445 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000446
Georg Brandl0a0cf162007-12-03 20:03:46 +0000447A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000448
Georg Brandl0a0cf162007-12-03 20:03:46 +0000449 from SimpleXMLRPCServer import SimpleXMLRPCServer
450
451 def add(x,y):
452 return x+y
453
454 def subtract(x, y):
455 return x-y
456
457 def multiply(x, y):
458 return x*y
459
460 def divide(x, y):
461 return x/y
462
463 # A simple server with simple arithmetic functions
464 server = SimpleXMLRPCServer(("localhost", 8000))
465 print "Listening on port 8000..."
466 server.register_multicall_functions()
467 server.register_function(add, 'add')
468 server.register_function(subtract, 'subtract')
469 server.register_function(multiply, 'multiply')
470 server.register_function(divide, 'divide')
471 server.serve_forever()
472
473The client code for the preceding server::
474
475 import xmlrpclib
476
477 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
478 multicall = xmlrpclib.MultiCall(proxy)
479 multicall.add(7,3)
480 multicall.subtract(7,3)
481 multicall.multiply(7,3)
482 multicall.divide(7,3)
483 result = multicall()
484
485 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000486
487
488Convenience Functions
489---------------------
490
491
492.. function:: boolean(value)
493
494 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
495 ``False``.
496
497
498.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
499
500 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
501 is true. *params* can be either a tuple of arguments or an instance of the
502 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
503 can be returned, meaning that *params* must be of length 1. *encoding*, if
504 supplied, is the encoding to use in the generated XML; the default is UTF-8.
505 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
506 it via an extension, provide a true value for *allow_none*.
507
508
509.. function:: loads(data[, use_datetime])
510
511 Convert an XML-RPC request or response into Python objects, a ``(params,
512 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
513 ``None`` if no method name is present in the packet. If the XML-RPC packet
514 represents a fault condition, this function will raise a :exc:`Fault` exception.
515 The *use_datetime* flag can be used to cause date/time values to be presented as
516 :class:`datetime.datetime` objects; this is false by default. Note that even if
517 you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time`
518 objects, they are converted to :class:`DateTime` objects internally, so only
519 :class:`datetime.datetime` objects will be returned.
520
521 .. versionchanged:: 2.5
522 The *use_datetime* flag was added.
523
524
525.. _xmlrpc-client-example:
526
527Example of Client Usage
528-----------------------
529
530::
531
532 # simple test program (from the XML-RPC specification)
533 from xmlrpclib import ServerProxy, Error
534
535 # server = ServerProxy("http://localhost:8000") # local server
536 server = ServerProxy("http://betty.userland.com")
537
538 print server
539
540 try:
541 print server.examples.getStateName(41)
542 except Error, v:
543 print "ERROR", v
544
545To access an XML-RPC server through a proxy, you need to define a custom
Georg Brandlb19be572007-12-29 10:57:00 +0000546transport. The following example shows how:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000547
Georg Brandlb19be572007-12-29 10:57:00 +0000548.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl8ec7f652007-08-15 14:28:01 +0000549
550::
551
552 import xmlrpclib, httplib
553
554 class ProxiedTransport(xmlrpclib.Transport):
555 def set_proxy(self, proxy):
556 self.proxy = proxy
557 def make_connection(self, host):
558 self.realhost = host
559 h = httplib.HTTP(self.proxy)
560 return h
561 def send_request(self, connection, handler, request_body):
562 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
563 def send_host(self, connection, host):
564 connection.putheader('Host', self.realhost)
565
566 p = ProxiedTransport()
567 p.set_proxy('proxy-server:8080')
568 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
569 print server.currentTime.getCurrentTime()
570
Georg Brandl0a0cf162007-12-03 20:03:46 +0000571
572Example of Client and Server Usage
573----------------------------------
574
575See :ref:`simplexmlrpcserver-example`.
576
577