blob: c06345e0a5230ab026500ee972c1c24fd8789a45 [file] [log] [blame]
Georg Brandl38eceaa2008-05-26 11:14:17 +00001:mod:`xmlrpc.client` --- XML-RPC client access
2==============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Georg Brandl38eceaa2008-05-26 11:14:17 +00004.. module:: xmlrpc.client
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: XML-RPC client access.
6.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
7.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
8
9
Christian Heimes5b5e81c2007-12-31 16:14:33 +000010.. XXX Not everything is documented yet. It might be good to describe
Florent Xicluna61665192011-11-15 20:53:25 +010011 Marshaller, Unmarshaller, getparser and Transport.
Georg Brandl116aa622007-08-15 14:28:22 +000012
Raymond Hettinger3029aff2011-02-10 08:09:36 +000013**Source code:** :source:`Lib/xmlrpc/client.py`
14
15--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +000017XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
18transport. With it, a client can call methods with parameters on a remote
19server (the server is named by a URI) and get back structured data. This module
20supports writing XML-RPC client code; it handles all the details of translating
21between conformable Python objects and XML on the wire.
22
23
Christian Heimes7380a672013-03-26 17:35:55 +010024.. warning::
25
26 The :mod:`xmlrpc.client` module is not secure against maliciously
27 constructed data. If you need to parse untrusted or unauthenticated data see
28 :ref:`xml-vulnerabilities`.
29
Benjamin Peterson4ffb0752014-11-03 14:29:33 -050030.. versionchanged:: 3.4.3
Benjamin Peterson77a75b32014-10-13 11:54:50 -040031
Benjamin Peterson4ffb0752014-11-03 14:29:33 -050032 For https URIs, :mod:`xmlrpc.client` now performs all the necessary
33 certificate and hostname checks by default
Christian Heimes7380a672013-03-26 17:35:55 +010034
Florent Xicluna61665192011-11-15 20:53:25 +010035.. class:: ServerProxy(uri, transport=None, encoding=None, verbose=False, \
36 allow_none=False, use_datetime=False, \
37 use_builtin_types=False)
38
39 .. versionchanged:: 3.3
40 The *use_builtin_types* flag was added.
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 A :class:`ServerProxy` instance is an object that manages communication with a
43 remote XML-RPC server. The required first argument is a URI (Uniform Resource
44 Indicator), and will normally be the URL of the server. The optional second
45 argument is a transport factory instance; by default it is an internal
46 :class:`SafeTransport` instance for https: URLs and an internal HTTP
47 :class:`Transport` instance otherwise. The optional third argument is an
48 encoding, by default UTF-8. The optional fourth argument is a debugging flag.
49 If *allow_none* is true, the Python constant ``None`` will be translated into
50 XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
51 a commonly-used extension to the XML-RPC specification, but isn't supported by
52 all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
Florent Xicluna61665192011-11-15 20:53:25 +010053 description. The *use_builtin_types* flag can be used to cause date/time values
54 to be presented as :class:`datetime.datetime` objects and binary data to be
55 presented as :class:`bytes` objects; this flag is false by default.
56 :class:`datetime.datetime` and :class:`bytes` objects may be passed to calls.
57
58 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
59 applies only to date/time values.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
62 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
63 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
64 the remote server as part of the connection process when invoking an XML-RPC
65 method. You only need to use this if the remote server requires a Basic
66 Authentication user and password.
67
68 The returned instance is a proxy object with methods that can be used to invoke
69 corresponding RPC calls on the remote server. If the remote server supports the
70 introspection API, the proxy can also be used to query the remote server for the
71 methods it supports (service discovery) and fetch other server-associated
72 metadata.
73
74 :class:`ServerProxy` instance methods take Python basic types and objects as
75 arguments and return Python basic types and classes. Types that are conformable
76 (e.g. that can be marshalled through XML), include the following (and except
77 where noted, they are unmarshalled as the same Python type):
78
Georg Brandl44ea77b2013-03-28 13:28:44 +010079 .. tabularcolumns:: |l|L|
80
Georg Brandl116aa622007-08-15 14:28:22 +000081 +---------------------------------+---------------------------------------------+
82 | Name | Meaning |
83 +=================================+=============================================+
84 | :const:`boolean` | The :const:`True` and :const:`False` |
85 | | constants |
86 +---------------------------------+---------------------------------------------+
87 | :const:`integers` | Pass in directly |
88 +---------------------------------+---------------------------------------------+
89 | :const:`floating-point numbers` | Pass in directly |
90 +---------------------------------+---------------------------------------------+
91 | :const:`strings` | Pass in directly |
92 +---------------------------------+---------------------------------------------+
93 | :const:`arrays` | Any Python sequence type containing |
94 | | conformable elements. Arrays are returned |
95 | | as lists |
96 +---------------------------------+---------------------------------------------+
97 | :const:`structures` | A Python dictionary. Keys must be strings, |
98 | | values may be any conformable type. Objects |
99 | | of user-defined classes can be passed in; |
100 | | only their *__dict__* attribute is |
101 | | transmitted. |
102 +---------------------------------+---------------------------------------------+
Florent Xicluna61665192011-11-15 20:53:25 +0100103 | :const:`dates` | In seconds since the epoch. Pass in an |
104 | | instance of the :class:`DateTime` class or |
Christian Heimes05e8be12008-02-23 18:30:17 +0000105 | | a :class:`datetime.datetime` instance. |
Georg Brandl116aa622007-08-15 14:28:22 +0000106 +---------------------------------+---------------------------------------------+
Florent Xicluna61665192011-11-15 20:53:25 +0100107 | :const:`binary data` | Pass in an instance of the :class:`Binary` |
108 | | wrapper class or a :class:`bytes` instance. |
Georg Brandl116aa622007-08-15 14:28:22 +0000109 +---------------------------------+---------------------------------------------+
110
111 This is the full set of data types supported by XML-RPC. Method calls may also
112 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
113 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
114 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
Georg Brandl38eceaa2008-05-26 11:14:17 +0000115 :exc:`Error`. Note that the xmlrpc client module currently does not marshal
Georg Brandl22b34312009-07-26 14:54:51 +0000116 instances of subclasses of built-in types.
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
119 will be automatically escaped. However, it's the caller's responsibility to
120 ensure that the string is free of characters that aren't allowed in XML, such as
121 the control characters with ASCII values between 0 and 31 (except, of course,
122 tab, newline and carriage return); failing to do this will result in an XML-RPC
Florent Xicluna61665192011-11-15 20:53:25 +0100123 request that isn't well-formed XML. If you have to pass arbitrary bytes
124 via XML-RPC, use the :class:`bytes` class or the class:`Binary` wrapper class
125 described below.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
128 compatibility. New code should use :class:`ServerProxy`.
129
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131.. seealso::
132
133 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000134 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000135 Contains pretty much everything an XML-RPC client developer needs to know.
136
Christian Heimesa62da1d2008-01-12 19:39:10 +0000137 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
138 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000140 `XML-RPC Specification <http://www.xmlrpc.com/spec>`_
141 The official specification.
142
143 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
144 Fredrik Lundh's "unofficial errata, intended to clarify certain
145 details in the XML-RPC specification, as well as hint at
146 'best practices' to use when designing your own XML-RPC
147 implementations."
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149.. _serverproxy-objects:
150
151ServerProxy Objects
152-------------------
153
154A :class:`ServerProxy` instance has a method corresponding to each remote
155procedure call accepted by the XML-RPC server. Calling the method performs an
156RPC, dispatched by both name and argument signature (e.g. the same method name
157can be overloaded with multiple argument signatures). The RPC finishes by
158returning a value, which may be either returned data in a conformant type or a
159:class:`Fault` or :class:`ProtocolError` object indicating an error.
160
161Servers that support the XML introspection API support some common methods
Senthil Kumarana6bac952011-07-04 11:28:30 -0700162grouped under the reserved :attr:`system` attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164
165.. method:: ServerProxy.system.listMethods()
166
167 This method returns a list of strings, one for each (non-system) method
168 supported by the XML-RPC server.
169
170
171.. method:: ServerProxy.system.methodSignature(name)
172
173 This method takes one parameter, the name of a method implemented by the XML-RPC
Georg Brandl94606482009-05-04 20:46:44 +0000174 server. It returns an array of possible signatures for this method. A signature
Georg Brandl116aa622007-08-15 14:28:22 +0000175 is an array of types. The first of these types is the return type of the method,
176 the rest are parameters.
177
178 Because multiple signatures (ie. overloading) is permitted, this method returns
179 a list of signatures rather than a singleton.
180
181 Signatures themselves are restricted to the top level parameters expected by a
182 method. For instance if a method expects one array of structs as a parameter,
183 and it returns a string, its signature is simply "string, array". If it expects
184 three integers and returns a string, its signature is "string, int, int, int".
185
186 If no signature is defined for the method, a non-array value is returned. In
187 Python this means that the type of the returned value will be something other
Georg Brandl94606482009-05-04 20:46:44 +0000188 than list.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
191.. method:: ServerProxy.system.methodHelp(name)
192
193 This method takes one parameter, the name of a method implemented by the XML-RPC
194 server. It returns a documentation string describing the use of that method. If
195 no such string is available, an empty string is returned. The documentation
196 string may contain HTML markup.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000199A working example follows. The server code::
200
Georg Brandl38eceaa2008-05-26 11:14:17 +0000201 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000202
203 def is_even(n):
204 return n%2 == 0
205
206 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000207 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000208 server.register_function(is_even, "is_even")
209 server.serve_forever()
210
211The client code for the preceding server::
212
Georg Brandl38eceaa2008-05-26 11:14:17 +0000213 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000214
Georg Brandl38eceaa2008-05-26 11:14:17 +0000215 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Georg Brandlf6945182008-02-01 11:56:49 +0000216 print("3 is even: %s" % str(proxy.is_even(3)))
217 print("100 is even: %s" % str(proxy.is_even(100)))
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219.. _datetime-objects:
220
221DateTime Objects
222----------------
223
Christian Heimes05e8be12008-02-23 18:30:17 +0000224This class may be initialized with seconds since the epoch, a time
225tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
226instance. It has the following methods, supported mainly for internal
227use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
230.. method:: DateTime.decode(string)
231
232 Accept a string as the instance's new time value.
233
234
235.. method:: DateTime.encode(out)
236
237 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
238 object.
239
Georg Brandl05f5ab72008-09-24 09:11:47 +0000240It also supports certain of Python's built-in operators through rich comparison
Georg Brandl116aa622007-08-15 14:28:22 +0000241and :meth:`__repr__` methods.
242
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000243A working example follows. The server code::
244
245 import datetime
Georg Brandl38eceaa2008-05-26 11:14:17 +0000246 from xmlrpc.server import SimpleXMLRPCServer
247 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000248
249 def today():
250 today = datetime.datetime.today()
Georg Brandl38eceaa2008-05-26 11:14:17 +0000251 return xmlrpc.client.DateTime(today)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000252
253 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000254 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000255 server.register_function(today, "today")
256 server.serve_forever()
257
258The client code for the preceding server::
259
Georg Brandl38eceaa2008-05-26 11:14:17 +0000260 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000261 import datetime
262
Georg Brandl38eceaa2008-05-26 11:14:17 +0000263 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000264
265 today = proxy.today()
266 # convert the ISO8601 string to a datetime object
267 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
Georg Brandlf6945182008-02-01 11:56:49 +0000268 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270.. _binary-objects:
271
272Binary Objects
273--------------
274
Florent Xicluna61665192011-11-15 20:53:25 +0100275This class may be initialized from bytes data (which may include NULs). The
Georg Brandl116aa622007-08-15 14:28:22 +0000276primary access to the content of a :class:`Binary` object is provided by an
277attribute:
278
279
280.. attribute:: Binary.data
281
282 The binary data encapsulated by the :class:`Binary` instance. The data is
Florent Xicluna61665192011-11-15 20:53:25 +0100283 provided as a :class:`bytes` object.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285:class:`Binary` objects have the following methods, supported mainly for
286internal use by the marshalling/unmarshalling code:
287
288
Florent Xicluna61665192011-11-15 20:53:25 +0100289.. method:: Binary.decode(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Florent Xicluna61665192011-11-15 20:53:25 +0100291 Accept a base64 :class:`bytes` object and decode it as the instance's new data.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
294.. method:: Binary.encode(out)
295
296 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
297
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000298 The encoded data will have newlines every 76 characters as per
299 `RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
300 which was the de facto standard base64 specification when the
301 XML-RPC spec was written.
302
Georg Brandl05f5ab72008-09-24 09:11:47 +0000303It also supports certain of Python's built-in operators through :meth:`__eq__`
304and :meth:`__ne__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000306Example usage of the binary objects. We're going to transfer an image over
307XMLRPC::
308
Georg Brandl38eceaa2008-05-26 11:14:17 +0000309 from xmlrpc.server import SimpleXMLRPCServer
310 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000311
312 def python_logo():
Victor Stinner757db832010-01-30 02:16:55 +0000313 with open("python_logo.jpg", "rb") as handle:
314 return xmlrpc.client.Binary(handle.read())
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000315
316 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000317 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000318 server.register_function(python_logo, 'python_logo')
319
320 server.serve_forever()
321
322The client gets the image and saves it to a file::
323
Georg Brandl38eceaa2008-05-26 11:14:17 +0000324 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000325
Georg Brandl38eceaa2008-05-26 11:14:17 +0000326 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Victor Stinner757db832010-01-30 02:16:55 +0000327 with open("fetched_python_logo.jpg", "wb") as handle:
328 handle.write(proxy.python_logo().data)
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. _fault-objects:
331
332Fault Objects
333-------------
334
335A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
Senthil Kumarana6bac952011-07-04 11:28:30 -0700336objects have the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338
339.. attribute:: Fault.faultCode
340
341 A string indicating the fault type.
342
343
344.. attribute:: Fault.faultString
345
346 A string containing a diagnostic message associated with the fault.
347
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000348In the following example we're going to intentionally cause a :exc:`Fault` by
349returning a complex type object. The server code::
350
Georg Brandl38eceaa2008-05-26 11:14:17 +0000351 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000352
353 # A marshalling error is going to occur because we're returning a
354 # complex number
355 def add(x,y):
356 return x+y+0j
357
358 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000359 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000360 server.register_function(add, 'add')
361
362 server.serve_forever()
363
364The client code for the preceding server::
365
Georg Brandl38eceaa2008-05-26 11:14:17 +0000366 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000367
Georg Brandl38eceaa2008-05-26 11:14:17 +0000368 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000369 try:
370 proxy.add(2, 5)
Georg Brandl0dedf452009-05-22 16:44:06 +0000371 except xmlrpc.client.Fault as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000372 print("A fault occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000373 print("Fault code: %d" % err.faultCode)
374 print("Fault string: %s" % err.faultString)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000375
376
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378.. _protocol-error-objects:
379
380ProtocolError Objects
381---------------------
382
383A :class:`ProtocolError` object describes a protocol error in the underlying
384transport layer (such as a 404 'not found' error if the server named by the URI
Senthil Kumarana6bac952011-07-04 11:28:30 -0700385does not exist). It has the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387
388.. attribute:: ProtocolError.url
389
390 The URI or URL that triggered the error.
391
392
393.. attribute:: ProtocolError.errcode
394
395 The error code.
396
397
398.. attribute:: ProtocolError.errmsg
399
400 The error message or diagnostic string.
401
402
403.. attribute:: ProtocolError.headers
404
Guido van Rossum460add42007-08-23 02:13:35 +0000405 A dict containing the headers of the HTTP/HTTPS request that triggered the
Georg Brandl116aa622007-08-15 14:28:22 +0000406 error.
407
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000408In the following example we're going to intentionally cause a :exc:`ProtocolError`
409by providing an invalid URI::
410
Georg Brandl38eceaa2008-05-26 11:14:17 +0000411 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000412
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000413 # create a ServerProxy with an URI that doesn't respond to XMLRPC requests
414 proxy = xmlrpc.client.ServerProxy("http://google.com/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000415
416 try:
417 proxy.some_method()
Georg Brandl0dedf452009-05-22 16:44:06 +0000418 except xmlrpc.client.ProtocolError as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000419 print("A protocol error occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000420 print("URL: %s" % err.url)
421 print("HTTP/HTTPS headers: %s" % err.headers)
422 print("Error code: %d" % err.errcode)
423 print("Error message: %s" % err.errmsg)
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425MultiCall Objects
426-----------------
427
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200428The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
429remote server into a single request [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
432.. class:: MultiCall(server)
433
434 Create an object used to boxcar method calls. *server* is the eventual target of
435 the call. Calls can be made to the result object, but they will immediately
436 return ``None``, and only store the call name and parameters in the
437 :class:`MultiCall` object. Calling the object itself causes all stored calls to
438 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000439 is a :term:`generator`; iterating over this generator yields the individual
440 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400442A usage example of this class follows. The server code::
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Georg Brandl38eceaa2008-05-26 11:14:17 +0000444 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000445
Ezio Melotti79016e12013-08-08 15:45:56 +0300446 def add(x, y):
447 return x + y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000448
449 def subtract(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300450 return x - y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000451
452 def multiply(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300453 return x * y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000454
455 def divide(x, y):
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400456 return x // y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000457
458 # A simple server with simple arithmetic functions
459 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000460 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000461 server.register_multicall_functions()
462 server.register_function(add, 'add')
463 server.register_function(subtract, 'subtract')
464 server.register_function(multiply, 'multiply')
465 server.register_function(divide, 'divide')
466 server.serve_forever()
467
468The client code for the preceding server::
469
Georg Brandl38eceaa2008-05-26 11:14:17 +0000470 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000471
Georg Brandl38eceaa2008-05-26 11:14:17 +0000472 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
473 multicall = xmlrpc.client.MultiCall(proxy)
Ezio Melotti79016e12013-08-08 15:45:56 +0300474 multicall.add(7, 3)
475 multicall.subtract(7, 3)
476 multicall.multiply(7, 3)
477 multicall.divide(7, 3)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000478 result = multicall()
479
Ezio Melotti79016e12013-08-08 15:45:56 +0300480 print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482
483Convenience Functions
484---------------------
485
Georg Brandl7f01a132009-09-16 15:58:14 +0000486.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000487
488 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
489 is true. *params* can be either a tuple of arguments or an instance of the
490 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
491 can be returned, meaning that *params* must be of length 1. *encoding*, if
492 supplied, is the encoding to use in the generated XML; the default is UTF-8.
493 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
494 it via an extension, provide a true value for *allow_none*.
495
496
Florent Xicluna61665192011-11-15 20:53:25 +0100497.. function:: loads(data, use_datetime=False, use_builtin_types=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499 Convert an XML-RPC request or response into Python objects, a ``(params,
500 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
501 ``None`` if no method name is present in the packet. If the XML-RPC packet
502 represents a fault condition, this function will raise a :exc:`Fault` exception.
Florent Xicluna61665192011-11-15 20:53:25 +0100503 The *use_builtin_types* flag can be used to cause date/time values to be
504 presented as :class:`datetime.datetime` objects and binary data to be
505 presented as :class:`bytes` objects; this flag is false by default.
506
507 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
508 applies only to date/time values.
509
510 .. versionchanged:: 3.3
511 The *use_builtin_types* flag was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514.. _xmlrpc-client-example:
515
516Example of Client Usage
517-----------------------
518
519::
520
521 # simple test program (from the XML-RPC specification)
Georg Brandl38eceaa2008-05-26 11:14:17 +0000522 from xmlrpc.client import ServerProxy, Error
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524 # server = ServerProxy("http://localhost:8000") # local server
525 server = ServerProxy("http://betty.userland.com")
526
Collin Winterc79461b2007-09-01 23:34:30 +0000527 print(server)
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529 try:
Collin Winterc79461b2007-09-01 23:34:30 +0000530 print(server.examples.getStateName(41))
Georg Brandl116aa622007-08-15 14:28:22 +0000531 except Error as v:
Collin Winterc79461b2007-09-01 23:34:30 +0000532 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534To access an XML-RPC server through a proxy, you need to define a custom
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000535transport. The following example shows how:
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000537.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539::
540
Georg Brandl24420152008-05-26 16:32:26 +0000541 import xmlrpc.client, http.client
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Georg Brandl38eceaa2008-05-26 11:14:17 +0000543 class ProxiedTransport(xmlrpc.client.Transport):
Georg Brandl116aa622007-08-15 14:28:22 +0000544 def set_proxy(self, proxy):
545 self.proxy = proxy
546 def make_connection(self, host):
547 self.realhost = host
Georg Brandl06788c92009-01-03 21:31:47 +0000548 h = http.client.HTTP(self.proxy)
549 return h
Georg Brandl116aa622007-08-15 14:28:22 +0000550 def send_request(self, connection, handler, request_body):
551 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
552 def send_host(self, connection, host):
553 connection.putheader('Host', self.realhost)
554
555 p = ProxiedTransport()
556 p.set_proxy('proxy-server:8080')
Georg Brandl38eceaa2008-05-26 11:14:17 +0000557 server = xmlrpc.client.Server('http://time.xmlrpc.com/RPC2', transport=p)
Collin Winterc79461b2007-09-01 23:34:30 +0000558 print(server.currentTime.getCurrentTime())
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000560
561Example of Client and Server Usage
562----------------------------------
563
564See :ref:`simplexmlrpcserver-example`.
565
566
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200567.. rubric:: Footnotes
568
569.. [#] This approach has been first presented in `a discussion on xmlrpc.com
570 <http://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
571.. the link now points to webarchive since the one at
572.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
573.. doesn't reply)