blob: 32403819531aa82d02e4935de5fd229d30839f6a [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
8.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
9
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040010**Source code:** :source:`Lib/xmlrpc/client.py`
Georg Brandl116aa622007-08-15 14:28:22 +000011
Christian Heimes5b5e81c2007-12-31 16:14:33 +000012.. XXX Not everything is documented yet. It might be good to describe
Florent Xicluna61665192011-11-15 20:53:25 +010013 Marshaller, Unmarshaller, getparser and Transport.
Georg Brandl116aa622007-08-15 14:28:22 +000014
Raymond Hettinger3029aff2011-02-10 08:09:36 +000015--------------
16
Serhiy Storchakada7880a2016-05-07 08:44:15 +030017XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a
Georg Brandl116aa622007-08-15 14:28:22 +000018transport. 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 Petersone39bba22014-11-29 23:34:30 -050030.. versionchanged:: 3.5
Benjamin Peterson77a75b32014-10-13 11:54:50 -040031
Martin Panterfe289c02016-05-28 02:20:39 +000032 For HTTPS URIs, :mod:`xmlrpc.client` now performs all the necessary
Serhiy Storchakada7880a2016-05-07 08:44:15 +030033 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, \
Cédric Krierbeda52e2019-02-19 17:18:50 +010037 use_builtin_types=False, *, headers=(), context=None)
Georg Brandl116aa622007-08-15 14:28:22 +000038
39 A :class:`ServerProxy` instance is an object that manages communication with a
40 remote XML-RPC server. The required first argument is a URI (Uniform Resource
41 Indicator), and will normally be the URL of the server. The optional second
42 argument is a transport factory instance; by default it is an internal
43 :class:`SafeTransport` instance for https: URLs and an internal HTTP
44 :class:`Transport` instance otherwise. The optional third argument is an
45 encoding, by default UTF-8. The optional fourth argument is a debugging flag.
Serhiy Storchakada7880a2016-05-07 08:44:15 +030046
47 The following parameters govern the use of the returned proxy instance.
Georg Brandl116aa622007-08-15 14:28:22 +000048 If *allow_none* is true, the Python constant ``None`` will be translated into
49 XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
50 a commonly-used extension to the XML-RPC specification, but isn't supported by
Serhiy Storchakada7880a2016-05-07 08:44:15 +030051 all clients and servers; see `http://ontosys.com/xml-rpc/extensions.php
Serhiy Storchaka64099ea2016-05-07 10:05:02 +030052 <https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php>`_
Serhiy Storchakada7880a2016-05-07 08:44:15 +030053 for a description.
54 The *use_builtin_types* flag can be used to cause date/time values
Florent Xicluna61665192011-11-15 20:53:25 +010055 to be presented as :class:`datetime.datetime` objects and binary data to be
56 presented as :class:`bytes` objects; this flag is false by default.
Serhiy Storchakada7880a2016-05-07 08:44:15 +030057 :class:`datetime.datetime`, :class:`bytes` and :class:`bytearray` objects
58 may be passed to calls.
Cédric Krierbeda52e2019-02-19 17:18:50 +010059 The *headers* parameter is an optional sequence of HTTP headers to send with
60 each request, expressed as a sequence of 2-tuples representing the header
61 name and value. (e.g. `[('Header-Name', 'value')]`).
Florent Xicluna61665192011-11-15 20:53:25 +010062 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
63 applies only to date/time values.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Cédric Krierbeda52e2019-02-19 17:18:50 +010065.. versionchanged:: 3.3
66 The *use_builtin_types* flag was added.
67
68.. versionchanged:: 3.8
69 The *headers* parameter was added.
70
Georg Brandl116aa622007-08-15 14:28:22 +000071 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
72 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
73 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
74 the remote server as part of the connection process when invoking an XML-RPC
75 method. You only need to use this if the remote server requires a Basic
Martin Panterfe289c02016-05-28 02:20:39 +000076 Authentication user and password. If an HTTPS URL is provided, *context* may
Benjamin Petersonc1da3d12014-11-29 23:32:57 -050077 be :class:`ssl.SSLContext` and configures the SSL settings of the underlying
78 HTTPS connection.
Georg Brandl116aa622007-08-15 14:28:22 +000079
80 The returned instance is a proxy object with methods that can be used to invoke
81 corresponding RPC calls on the remote server. If the remote server supports the
82 introspection API, the proxy can also be used to query the remote server for the
83 methods it supports (service discovery) and fetch other server-associated
84 metadata.
85
Serhiy Storchakada7880a2016-05-07 08:44:15 +030086 Types that are conformable (e.g. that can be marshalled through XML),
87 include the following (and except where noted, they are unmarshalled
88 as the same Python type):
Georg Brandl116aa622007-08-15 14:28:22 +000089
Georg Brandl44ea77b2013-03-28 13:28:44 +010090 .. tabularcolumns:: |l|L|
91
Serhiy Storchakada7880a2016-05-07 08:44:15 +030092 +----------------------+-------------------------------------------------------+
93 | XML-RPC type | Python type |
94 +======================+=======================================================+
95 | ``boolean`` | :class:`bool` |
96 +----------------------+-------------------------------------------------------+
Serhiy Storchaka352601c2016-09-11 11:23:38 +030097 | ``int``, ``i1``, | :class:`int` in range from -2147483648 to 2147483647. |
98 | ``i2``, ``i4``, | Values get the ``<int>`` tag. |
99 | ``i8`` or | |
100 | ``biginteger`` | |
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300101 +----------------------+-------------------------------------------------------+
Serhiy Storchaka352601c2016-09-11 11:23:38 +0300102 | ``double`` or | :class:`float`. Values get the ``<double>`` tag. |
103 | ``float`` | |
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300104 +----------------------+-------------------------------------------------------+
105 | ``string`` | :class:`str` |
106 +----------------------+-------------------------------------------------------+
107 | ``array`` | :class:`list` or :class:`tuple` containing |
108 | | conformable elements. Arrays are returned as |
Serhiy Storchaka64099ea2016-05-07 10:05:02 +0300109 | | :class:`lists <list>`. |
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300110 +----------------------+-------------------------------------------------------+
111 | ``struct`` | :class:`dict`. Keys must be strings, values may be |
112 | | any conformable type. Objects of user-defined |
Serhiy Storchaka64099ea2016-05-07 10:05:02 +0300113 | | classes can be passed in; only their |
114 | | :attr:`~object.__dict__` attribute is transmitted. |
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300115 +----------------------+-------------------------------------------------------+
116 | ``dateTime.iso8601`` | :class:`DateTime` or :class:`datetime.datetime`. |
117 | | Returned type depends on values of |
118 | | *use_builtin_types* and *use_datetime* flags. |
119 +----------------------+-------------------------------------------------------+
120 | ``base64`` | :class:`Binary`, :class:`bytes` or |
121 | | :class:`bytearray`. Returned type depends on the |
122 | | value of the *use_builtin_types* flag. |
123 +----------------------+-------------------------------------------------------+
124 | ``nil`` | The ``None`` constant. Passing is allowed only if |
125 | | *allow_none* is true. |
126 +----------------------+-------------------------------------------------------+
Serhiy Storchaka352601c2016-09-11 11:23:38 +0300127 | ``bigdecimal`` | :class:`decimal.Decimal`. Returned type only. |
128 +----------------------+-------------------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130 This is the full set of data types supported by XML-RPC. Method calls may also
131 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
132 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
133 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
Georg Brandl38eceaa2008-05-26 11:14:17 +0000134 :exc:`Error`. Note that the xmlrpc client module currently does not marshal
Georg Brandl22b34312009-07-26 14:54:51 +0000135 instances of subclasses of built-in types.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
138 will be automatically escaped. However, it's the caller's responsibility to
139 ensure that the string is free of characters that aren't allowed in XML, such as
140 the control characters with ASCII values between 0 and 31 (except, of course,
141 tab, newline and carriage return); failing to do this will result in an XML-RPC
Florent Xicluna61665192011-11-15 20:53:25 +0100142 request that isn't well-formed XML. If you have to pass arbitrary bytes
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300143 via XML-RPC, use :class:`bytes` or :class:`bytearray` classes or the
144 :class:`Binary` wrapper class described below.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
147 compatibility. New code should use :class:`ServerProxy`.
148
Benjamin Petersone39bba22014-11-29 23:34:30 -0500149 .. versionchanged:: 3.5
Benjamin Petersonc1da3d12014-11-29 23:32:57 -0500150 Added the *context* argument.
151
Serhiy Storchaka352601c2016-09-11 11:23:38 +0300152 .. versionchanged:: 3.6
Serhiy Storchakab7e35352016-09-11 16:47:59 +0300153 Added support of type tags with prefixes (e.g. ``ex:nil``).
Xtreakc151f782018-06-16 10:38:31 +0530154 Added support of unmarshalling additional types used by Apache XML-RPC
Serhiy Storchaka352601c2016-09-11 11:23:38 +0300155 implementation for numerics: ``i1``, ``i2``, ``i8``, ``biginteger``,
156 ``float`` and ``bigdecimal``.
157 See http://ws.apache.org/xmlrpc/types.html for a description.
158
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160.. seealso::
161
162 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000163 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000164 Contains pretty much everything an XML-RPC client developer needs to know.
165
Christian Heimesa62da1d2008-01-12 19:39:10 +0000166 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
167 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Georg Brandl5d941342016-02-26 19:37:12 +0100169 `XML-RPC Specification <http://xmlrpc.scripting.com/spec.html>`_
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000170 The official specification.
171
172 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
173 Fredrik Lundh's "unofficial errata, intended to clarify certain
174 details in the XML-RPC specification, as well as hint at
175 'best practices' to use when designing your own XML-RPC
176 implementations."
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. _serverproxy-objects:
179
180ServerProxy Objects
181-------------------
182
183A :class:`ServerProxy` instance has a method corresponding to each remote
184procedure call accepted by the XML-RPC server. Calling the method performs an
185RPC, dispatched by both name and argument signature (e.g. the same method name
186can be overloaded with multiple argument signatures). The RPC finishes by
187returning a value, which may be either returned data in a conformant type or a
188:class:`Fault` or :class:`ProtocolError` object indicating an error.
189
190Servers that support the XML introspection API support some common methods
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300191grouped under the reserved :attr:`~ServerProxy.system` attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193
194.. method:: ServerProxy.system.listMethods()
195
196 This method returns a list of strings, one for each (non-system) method
197 supported by the XML-RPC server.
198
199
200.. method:: ServerProxy.system.methodSignature(name)
201
202 This method takes one parameter, the name of a method implemented by the XML-RPC
Georg Brandl94606482009-05-04 20:46:44 +0000203 server. It returns an array of possible signatures for this method. A signature
Georg Brandl116aa622007-08-15 14:28:22 +0000204 is an array of types. The first of these types is the return type of the method,
205 the rest are parameters.
206
207 Because multiple signatures (ie. overloading) is permitted, this method returns
208 a list of signatures rather than a singleton.
209
210 Signatures themselves are restricted to the top level parameters expected by a
211 method. For instance if a method expects one array of structs as a parameter,
212 and it returns a string, its signature is simply "string, array". If it expects
213 three integers and returns a string, its signature is "string, int, int, int".
214
215 If no signature is defined for the method, a non-array value is returned. In
216 Python this means that the type of the returned value will be something other
Georg Brandl94606482009-05-04 20:46:44 +0000217 than list.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219
220.. method:: ServerProxy.system.methodHelp(name)
221
222 This method takes one parameter, the name of a method implemented by the XML-RPC
223 server. It returns a documentation string describing the use of that method. If
224 no such string is available, an empty string is returned. The documentation
225 string may contain HTML markup.
226
Brett Cannon33a40002014-03-21 11:24:40 -0400227.. versionchanged:: 3.5
228
229 Instances of :class:`ServerProxy` support the :term:`context manager` protocol
230 for closing the underlying transport.
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000233A working example follows. The server code::
234
Georg Brandl38eceaa2008-05-26 11:14:17 +0000235 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000236
237 def is_even(n):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300238 return n % 2 == 0
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000239
240 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000241 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000242 server.register_function(is_even, "is_even")
243 server.serve_forever()
244
245The client code for the preceding server::
246
Georg Brandl38eceaa2008-05-26 11:14:17 +0000247 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000248
Brett Cannon33a40002014-03-21 11:24:40 -0400249 with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
250 print("3 is even: %s" % str(proxy.is_even(3)))
251 print("100 is even: %s" % str(proxy.is_even(100)))
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253.. _datetime-objects:
254
255DateTime Objects
256----------------
257
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300258.. class:: DateTime
259
260 This class may be initialized with seconds since the epoch, a time
261 tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
262 instance. It has the following methods, supported mainly for internal
263 use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300266 .. method:: decode(string)
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300268 Accept a string as the instance's new time value.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300271 .. method:: encode(out)
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300273 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
274 object.
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300276 It also supports certain of Python's built-in operators through rich comparison
277 and :meth:`__repr__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000279A working example follows. The server code::
280
281 import datetime
Georg Brandl38eceaa2008-05-26 11:14:17 +0000282 from xmlrpc.server import SimpleXMLRPCServer
283 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000284
285 def today():
286 today = datetime.datetime.today()
Georg Brandl38eceaa2008-05-26 11:14:17 +0000287 return xmlrpc.client.DateTime(today)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000288
289 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000290 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000291 server.register_function(today, "today")
292 server.serve_forever()
293
294The client code for the preceding server::
295
Georg Brandl38eceaa2008-05-26 11:14:17 +0000296 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000297 import datetime
298
Georg Brandl38eceaa2008-05-26 11:14:17 +0000299 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000300
301 today = proxy.today()
302 # convert the ISO8601 string to a datetime object
303 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
Georg Brandlf6945182008-02-01 11:56:49 +0000304 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306.. _binary-objects:
307
308Binary Objects
309--------------
310
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300311.. class:: Binary
312
313 This class may be initialized from bytes data (which may include NULs). The
314 primary access to the content of a :class:`Binary` object is provided by an
315 attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300318 .. attribute:: data
Georg Brandl116aa622007-08-15 14:28:22 +0000319
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300320 The binary data encapsulated by the :class:`Binary` instance. The data is
321 provided as a :class:`bytes` object.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300323 :class:`Binary` objects have the following methods, supported mainly for
324 internal use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300327 .. method:: decode(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300329 Accept a base64 :class:`bytes` object and decode it as the instance's new data.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300332 .. method:: encode(out)
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300334 Write the XML-RPC base 64 encoding of this binary item to the *out* stream object.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300336 The encoded data will have newlines every 76 characters as per
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +0300337 :rfc:`RFC 2045 section 6.8 <2045#section-6.8>`,
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300338 which was the de facto standard base64 specification when the
339 XML-RPC spec was written.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000340
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300341 It also supports certain of Python's built-in operators through :meth:`__eq__`
342 and :meth:`__ne__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000344Example usage of the binary objects. We're going to transfer an image over
345XMLRPC::
346
Georg Brandl38eceaa2008-05-26 11:14:17 +0000347 from xmlrpc.server import SimpleXMLRPCServer
348 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000349
350 def python_logo():
Victor Stinner757db832010-01-30 02:16:55 +0000351 with open("python_logo.jpg", "rb") as handle:
352 return xmlrpc.client.Binary(handle.read())
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000353
354 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000355 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000356 server.register_function(python_logo, 'python_logo')
357
358 server.serve_forever()
359
360The client gets the image and saves it to a file::
361
Georg Brandl38eceaa2008-05-26 11:14:17 +0000362 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000363
Georg Brandl38eceaa2008-05-26 11:14:17 +0000364 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Victor Stinner757db832010-01-30 02:16:55 +0000365 with open("fetched_python_logo.jpg", "wb") as handle:
366 handle.write(proxy.python_logo().data)
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368.. _fault-objects:
369
370Fault Objects
371-------------
372
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300373.. class:: Fault
374
375 A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
376 objects have the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300379 .. attribute:: faultCode
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300381 A string indicating the fault type.
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300384 .. attribute:: faultString
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300386 A string containing a diagnostic message associated with the fault.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000388In the following example we're going to intentionally cause a :exc:`Fault` by
389returning a complex type object. The server code::
390
Georg Brandl38eceaa2008-05-26 11:14:17 +0000391 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000392
393 # A marshalling error is going to occur because we're returning a
394 # complex number
Serhiy Storchakadba90392016-05-10 12:01:23 +0300395 def add(x, y):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000396 return x+y+0j
397
398 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000399 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000400 server.register_function(add, 'add')
401
402 server.serve_forever()
403
404The client code for the preceding server::
405
Georg Brandl38eceaa2008-05-26 11:14:17 +0000406 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000407
Georg Brandl38eceaa2008-05-26 11:14:17 +0000408 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000409 try:
410 proxy.add(2, 5)
Georg Brandl0dedf452009-05-22 16:44:06 +0000411 except xmlrpc.client.Fault as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000412 print("A fault occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000413 print("Fault code: %d" % err.faultCode)
414 print("Fault string: %s" % err.faultString)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000415
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418.. _protocol-error-objects:
419
420ProtocolError Objects
421---------------------
422
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300423.. class:: ProtocolError
424
425 A :class:`ProtocolError` object describes a protocol error in the underlying
426 transport layer (such as a 404 'not found' error if the server named by the URI
427 does not exist). It has the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300430 .. attribute:: url
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300432 The URI or URL that triggered the error.
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300435 .. attribute:: errcode
Georg Brandl116aa622007-08-15 14:28:22 +0000436
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300437 The error code.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300440 .. attribute:: errmsg
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300442 The error message or diagnostic string.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300445 .. attribute:: headers
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300447 A dict containing the headers of the HTTP/HTTPS request that triggered the
448 error.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000450In the following example we're going to intentionally cause a :exc:`ProtocolError`
451by providing an invalid URI::
452
Georg Brandl38eceaa2008-05-26 11:14:17 +0000453 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000454
Martin Panter6245cb32016-04-15 02:14:19 +0000455 # create a ServerProxy with a URI that doesn't respond to XMLRPC requests
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000456 proxy = xmlrpc.client.ServerProxy("http://google.com/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000457
458 try:
459 proxy.some_method()
Georg Brandl0dedf452009-05-22 16:44:06 +0000460 except xmlrpc.client.ProtocolError as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000461 print("A protocol error occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000462 print("URL: %s" % err.url)
463 print("HTTP/HTTPS headers: %s" % err.headers)
464 print("Error code: %d" % err.errcode)
465 print("Error message: %s" % err.errmsg)
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467MultiCall Objects
468-----------------
469
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200470The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
471remote server into a single request [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000472
473
474.. class:: MultiCall(server)
475
476 Create an object used to boxcar method calls. *server* is the eventual target of
477 the call. Calls can be made to the result object, but they will immediately
478 return ``None``, and only store the call name and parameters in the
479 :class:`MultiCall` object. Calling the object itself causes all stored calls to
480 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000481 is a :term:`generator`; iterating over this generator yields the individual
482 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400484A usage example of this class follows. The server code::
Georg Brandl116aa622007-08-15 14:28:22 +0000485
Georg Brandl38eceaa2008-05-26 11:14:17 +0000486 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000487
Ezio Melotti79016e12013-08-08 15:45:56 +0300488 def add(x, y):
489 return x + y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000490
491 def subtract(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300492 return x - y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000493
494 def multiply(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300495 return x * y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000496
497 def divide(x, y):
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400498 return x // y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000499
500 # A simple server with simple arithmetic functions
501 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000502 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000503 server.register_multicall_functions()
504 server.register_function(add, 'add')
505 server.register_function(subtract, 'subtract')
506 server.register_function(multiply, 'multiply')
507 server.register_function(divide, 'divide')
508 server.serve_forever()
509
510The client code for the preceding server::
511
Georg Brandl38eceaa2008-05-26 11:14:17 +0000512 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000513
Georg Brandl38eceaa2008-05-26 11:14:17 +0000514 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
515 multicall = xmlrpc.client.MultiCall(proxy)
Ezio Melotti79016e12013-08-08 15:45:56 +0300516 multicall.add(7, 3)
517 multicall.subtract(7, 3)
518 multicall.multiply(7, 3)
519 multicall.divide(7, 3)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000520 result = multicall()
521
Ezio Melotti79016e12013-08-08 15:45:56 +0300522 print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524
525Convenience Functions
526---------------------
527
Georg Brandl7f01a132009-09-16 15:58:14 +0000528.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
531 is true. *params* can be either a tuple of arguments or an instance of the
532 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
533 can be returned, meaning that *params* must be of length 1. *encoding*, if
534 supplied, is the encoding to use in the generated XML; the default is UTF-8.
535 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
536 it via an extension, provide a true value for *allow_none*.
537
538
Florent Xicluna61665192011-11-15 20:53:25 +0100539.. function:: loads(data, use_datetime=False, use_builtin_types=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000540
541 Convert an XML-RPC request or response into Python objects, a ``(params,
542 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
543 ``None`` if no method name is present in the packet. If the XML-RPC packet
544 represents a fault condition, this function will raise a :exc:`Fault` exception.
Florent Xicluna61665192011-11-15 20:53:25 +0100545 The *use_builtin_types* flag can be used to cause date/time values to be
546 presented as :class:`datetime.datetime` objects and binary data to be
547 presented as :class:`bytes` objects; this flag is false by default.
548
549 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
550 applies only to date/time values.
551
552 .. versionchanged:: 3.3
553 The *use_builtin_types* flag was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556.. _xmlrpc-client-example:
557
558Example of Client Usage
559-----------------------
560
561::
562
563 # simple test program (from the XML-RPC specification)
Georg Brandl38eceaa2008-05-26 11:14:17 +0000564 from xmlrpc.client import ServerProxy, Error
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566 # server = ServerProxy("http://localhost:8000") # local server
Brett Cannon33a40002014-03-21 11:24:40 -0400567 with ServerProxy("http://betty.userland.com") as proxy:
Georg Brandl116aa622007-08-15 14:28:22 +0000568
Brett Cannon33a40002014-03-21 11:24:40 -0400569 print(proxy)
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Brett Cannon33a40002014-03-21 11:24:40 -0400571 try:
572 print(proxy.examples.getStateName(41))
573 except Error as v:
574 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Martin Panter1c5e7152016-02-22 09:04:22 +0000576To access an XML-RPC server through a HTTP proxy, you need to define a custom
Berker Peksag0aa78872016-10-09 18:18:21 +0300577transport. The following example shows how::
Georg Brandl116aa622007-08-15 14:28:22 +0000578
Berker Peksag0aa78872016-10-09 18:18:21 +0300579 import http.client
580 import xmlrpc.client
Georg Brandl116aa622007-08-15 14:28:22 +0000581
Georg Brandl38eceaa2008-05-26 11:14:17 +0000582 class ProxiedTransport(xmlrpc.client.Transport):
Berker Peksag0aa78872016-10-09 18:18:21 +0300583
584 def set_proxy(self, host, port=None, headers=None):
585 self.proxy = host, port
586 self.proxy_headers = headers
Serhiy Storchakadba90392016-05-10 12:01:23 +0300587
Georg Brandl116aa622007-08-15 14:28:22 +0000588 def make_connection(self, host):
Berker Peksag0aa78872016-10-09 18:18:21 +0300589 connection = http.client.HTTPConnection(*self.proxy)
590 connection.set_tunnel(host, headers=self.proxy_headers)
591 self._connection = host, connection
592 return connection
Serhiy Storchakadba90392016-05-10 12:01:23 +0300593
Berker Peksag0aa78872016-10-09 18:18:21 +0300594 transport = ProxiedTransport()
595 transport.set_proxy('proxy-server', 8080)
596 server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
597 print(server.examples.getStateName(41))
Georg Brandl116aa622007-08-15 14:28:22 +0000598
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000599
600Example of Client and Server Usage
601----------------------------------
602
603See :ref:`simplexmlrpcserver-example`.
604
605
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200606.. rubric:: Footnotes
607
608.. [#] This approach has been first presented in `a discussion on xmlrpc.com
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300609 <https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200610.. the link now points to webarchive since the one at
611.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
612.. doesn't reply)