blob: e7916d2bff5895b143a95cb3f05555099cb3bfa5 [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, \
Benjamin Petersonb7138e22014-11-29 23:38:17 -050037 use_builtin_types=False, *, context=None)
Florent Xicluna61665192011-11-15 20:53:25 +010038
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.
Serhiy Storchakada7880a2016-05-07 08:44:15 +030049
50 The following parameters govern the use of the returned proxy instance.
Georg Brandl116aa622007-08-15 14:28:22 +000051 If *allow_none* is true, the Python constant ``None`` will be translated into
52 XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
53 a commonly-used extension to the XML-RPC specification, but isn't supported by
Serhiy Storchakada7880a2016-05-07 08:44:15 +030054 all clients and servers; see `http://ontosys.com/xml-rpc/extensions.php
Serhiy Storchaka64099ea2016-05-07 10:05:02 +030055 <https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php>`_
Serhiy Storchakada7880a2016-05-07 08:44:15 +030056 for a description.
57 The *use_builtin_types* flag can be used to cause date/time values
Florent Xicluna61665192011-11-15 20:53:25 +010058 to be presented as :class:`datetime.datetime` objects and binary data to be
59 presented as :class:`bytes` objects; this flag is false by default.
Serhiy Storchakada7880a2016-05-07 08:44:15 +030060 :class:`datetime.datetime`, :class:`bytes` and :class:`bytearray` objects
61 may be passed to calls.
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
65 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
66 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
67 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
68 the remote server as part of the connection process when invoking an XML-RPC
69 method. You only need to use this if the remote server requires a Basic
Martin Panterfe289c02016-05-28 02:20:39 +000070 Authentication user and password. If an HTTPS URL is provided, *context* may
Benjamin Petersonc1da3d12014-11-29 23:32:57 -050071 be :class:`ssl.SSLContext` and configures the SSL settings of the underlying
72 HTTPS connection.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74 The returned instance is a proxy object with methods that can be used to invoke
75 corresponding RPC calls on the remote server. If the remote server supports the
76 introspection API, the proxy can also be used to query the remote server for the
77 methods it supports (service discovery) and fetch other server-associated
78 metadata.
79
Serhiy Storchakada7880a2016-05-07 08:44:15 +030080 Types that are conformable (e.g. that can be marshalled through XML),
81 include the following (and except where noted, they are unmarshalled
82 as the same Python type):
Georg Brandl116aa622007-08-15 14:28:22 +000083
Georg Brandl44ea77b2013-03-28 13:28:44 +010084 .. tabularcolumns:: |l|L|
85
Serhiy Storchakada7880a2016-05-07 08:44:15 +030086 +----------------------+-------------------------------------------------------+
87 | XML-RPC type | Python type |
88 +======================+=======================================================+
89 | ``boolean`` | :class:`bool` |
90 +----------------------+-------------------------------------------------------+
91 | ``int`` or ``i4`` | :class:`int` in range from -2147483648 to 2147483647. |
92 +----------------------+-------------------------------------------------------+
93 | ``double`` | :class:`float` |
94 +----------------------+-------------------------------------------------------+
95 | ``string`` | :class:`str` |
96 +----------------------+-------------------------------------------------------+
97 | ``array`` | :class:`list` or :class:`tuple` containing |
98 | | conformable elements. Arrays are returned as |
Serhiy Storchaka64099ea2016-05-07 10:05:02 +030099 | | :class:`lists <list>`. |
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300100 +----------------------+-------------------------------------------------------+
101 | ``struct`` | :class:`dict`. Keys must be strings, values may be |
102 | | any conformable type. Objects of user-defined |
Serhiy Storchaka64099ea2016-05-07 10:05:02 +0300103 | | classes can be passed in; only their |
104 | | :attr:`~object.__dict__` attribute is transmitted. |
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300105 +----------------------+-------------------------------------------------------+
106 | ``dateTime.iso8601`` | :class:`DateTime` or :class:`datetime.datetime`. |
107 | | Returned type depends on values of |
108 | | *use_builtin_types* and *use_datetime* flags. |
109 +----------------------+-------------------------------------------------------+
110 | ``base64`` | :class:`Binary`, :class:`bytes` or |
111 | | :class:`bytearray`. Returned type depends on the |
112 | | value of the *use_builtin_types* flag. |
113 +----------------------+-------------------------------------------------------+
114 | ``nil`` | The ``None`` constant. Passing is allowed only if |
115 | | *allow_none* is true. |
116 +----------------------+-------------------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 This is the full set of data types supported by XML-RPC. Method calls may also
119 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
120 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
121 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
Georg Brandl38eceaa2008-05-26 11:14:17 +0000122 :exc:`Error`. Note that the xmlrpc client module currently does not marshal
Georg Brandl22b34312009-07-26 14:54:51 +0000123 instances of subclasses of built-in types.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
126 will be automatically escaped. However, it's the caller's responsibility to
127 ensure that the string is free of characters that aren't allowed in XML, such as
128 the control characters with ASCII values between 0 and 31 (except, of course,
129 tab, newline and carriage return); failing to do this will result in an XML-RPC
Florent Xicluna61665192011-11-15 20:53:25 +0100130 request that isn't well-formed XML. If you have to pass arbitrary bytes
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300131 via XML-RPC, use :class:`bytes` or :class:`bytearray` classes or the
132 :class:`Binary` wrapper class described below.
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
135 compatibility. New code should use :class:`ServerProxy`.
136
Benjamin Petersone39bba22014-11-29 23:34:30 -0500137 .. versionchanged:: 3.5
Benjamin Petersonc1da3d12014-11-29 23:32:57 -0500138 Added the *context* argument.
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141.. seealso::
142
143 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000144 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000145 Contains pretty much everything an XML-RPC client developer needs to know.
146
Christian Heimesa62da1d2008-01-12 19:39:10 +0000147 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
148 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Georg Brandl5d941342016-02-26 19:37:12 +0100150 `XML-RPC Specification <http://xmlrpc.scripting.com/spec.html>`_
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000151 The official specification.
152
153 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
154 Fredrik Lundh's "unofficial errata, intended to clarify certain
155 details in the XML-RPC specification, as well as hint at
156 'best practices' to use when designing your own XML-RPC
157 implementations."
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159.. _serverproxy-objects:
160
161ServerProxy Objects
162-------------------
163
164A :class:`ServerProxy` instance has a method corresponding to each remote
165procedure call accepted by the XML-RPC server. Calling the method performs an
166RPC, dispatched by both name and argument signature (e.g. the same method name
167can be overloaded with multiple argument signatures). The RPC finishes by
168returning a value, which may be either returned data in a conformant type or a
169:class:`Fault` or :class:`ProtocolError` object indicating an error.
170
171Servers that support the XML introspection API support some common methods
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300172grouped under the reserved :attr:`~ServerProxy.system` attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174
175.. method:: ServerProxy.system.listMethods()
176
177 This method returns a list of strings, one for each (non-system) method
178 supported by the XML-RPC server.
179
180
181.. method:: ServerProxy.system.methodSignature(name)
182
183 This method takes one parameter, the name of a method implemented by the XML-RPC
Georg Brandl94606482009-05-04 20:46:44 +0000184 server. It returns an array of possible signatures for this method. A signature
Georg Brandl116aa622007-08-15 14:28:22 +0000185 is an array of types. The first of these types is the return type of the method,
186 the rest are parameters.
187
188 Because multiple signatures (ie. overloading) is permitted, this method returns
189 a list of signatures rather than a singleton.
190
191 Signatures themselves are restricted to the top level parameters expected by a
192 method. For instance if a method expects one array of structs as a parameter,
193 and it returns a string, its signature is simply "string, array". If it expects
194 three integers and returns a string, its signature is "string, int, int, int".
195
196 If no signature is defined for the method, a non-array value is returned. In
197 Python this means that the type of the returned value will be something other
Georg Brandl94606482009-05-04 20:46:44 +0000198 than list.
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200
201.. method:: ServerProxy.system.methodHelp(name)
202
203 This method takes one parameter, the name of a method implemented by the XML-RPC
204 server. It returns a documentation string describing the use of that method. If
205 no such string is available, an empty string is returned. The documentation
206 string may contain HTML markup.
207
Brett Cannon33a40002014-03-21 11:24:40 -0400208.. versionchanged:: 3.5
209
210 Instances of :class:`ServerProxy` support the :term:`context manager` protocol
211 for closing the underlying transport.
212
Georg Brandl116aa622007-08-15 14:28:22 +0000213
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000214A working example follows. The server code::
215
Georg Brandl38eceaa2008-05-26 11:14:17 +0000216 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000217
218 def is_even(n):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300219 return n % 2 == 0
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000220
221 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000222 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000223 server.register_function(is_even, "is_even")
224 server.serve_forever()
225
226The client code for the preceding server::
227
Georg Brandl38eceaa2008-05-26 11:14:17 +0000228 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000229
Brett Cannon33a40002014-03-21 11:24:40 -0400230 with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
231 print("3 is even: %s" % str(proxy.is_even(3)))
232 print("100 is even: %s" % str(proxy.is_even(100)))
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234.. _datetime-objects:
235
236DateTime Objects
237----------------
238
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300239.. class:: DateTime
240
241 This class may be initialized with seconds since the epoch, a time
242 tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
243 instance. It has the following methods, supported mainly for internal
244 use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300247 .. method:: decode(string)
Georg Brandl116aa622007-08-15 14:28:22 +0000248
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300249 Accept a string as the instance's new time value.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300252 .. method:: encode(out)
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300254 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
255 object.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300257 It also supports certain of Python's built-in operators through rich comparison
258 and :meth:`__repr__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000260A working example follows. The server code::
261
262 import datetime
Georg Brandl38eceaa2008-05-26 11:14:17 +0000263 from xmlrpc.server import SimpleXMLRPCServer
264 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000265
266 def today():
267 today = datetime.datetime.today()
Georg Brandl38eceaa2008-05-26 11:14:17 +0000268 return xmlrpc.client.DateTime(today)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000269
270 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000271 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000272 server.register_function(today, "today")
273 server.serve_forever()
274
275The client code for the preceding server::
276
Georg Brandl38eceaa2008-05-26 11:14:17 +0000277 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000278 import datetime
279
Georg Brandl38eceaa2008-05-26 11:14:17 +0000280 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000281
282 today = proxy.today()
283 # convert the ISO8601 string to a datetime object
284 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
Georg Brandlf6945182008-02-01 11:56:49 +0000285 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287.. _binary-objects:
288
289Binary Objects
290--------------
291
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300292.. class:: Binary
293
294 This class may be initialized from bytes data (which may include NULs). The
295 primary access to the content of a :class:`Binary` object is provided by an
296 attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300299 .. attribute:: data
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300301 The binary data encapsulated by the :class:`Binary` instance. The data is
302 provided as a :class:`bytes` object.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300304 :class:`Binary` objects have the following methods, supported mainly for
305 internal use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300308 .. method:: decode(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300310 Accept a base64 :class:`bytes` object and decode it as the instance's new data.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300313 .. method:: encode(out)
Georg Brandl116aa622007-08-15 14:28:22 +0000314
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300315 Write the XML-RPC base 64 encoding of this binary item to the *out* stream object.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300317 The encoded data will have newlines every 76 characters as per
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300318 `RFC 2045 section 6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_,
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300319 which was the de facto standard base64 specification when the
320 XML-RPC spec was written.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000321
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300322 It also supports certain of Python's built-in operators through :meth:`__eq__`
323 and :meth:`__ne__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000325Example usage of the binary objects. We're going to transfer an image over
326XMLRPC::
327
Georg Brandl38eceaa2008-05-26 11:14:17 +0000328 from xmlrpc.server import SimpleXMLRPCServer
329 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000330
331 def python_logo():
Victor Stinner757db832010-01-30 02:16:55 +0000332 with open("python_logo.jpg", "rb") as handle:
333 return xmlrpc.client.Binary(handle.read())
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000334
335 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000336 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000337 server.register_function(python_logo, 'python_logo')
338
339 server.serve_forever()
340
341The client gets the image and saves it to a file::
342
Georg Brandl38eceaa2008-05-26 11:14:17 +0000343 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000344
Georg Brandl38eceaa2008-05-26 11:14:17 +0000345 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Victor Stinner757db832010-01-30 02:16:55 +0000346 with open("fetched_python_logo.jpg", "wb") as handle:
347 handle.write(proxy.python_logo().data)
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349.. _fault-objects:
350
351Fault Objects
352-------------
353
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300354.. class:: Fault
355
356 A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
357 objects have the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300360 .. attribute:: faultCode
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300362 A string indicating the fault type.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300365 .. attribute:: faultString
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300367 A string containing a diagnostic message associated with the fault.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000369In the following example we're going to intentionally cause a :exc:`Fault` by
370returning a complex type object. The server code::
371
Georg Brandl38eceaa2008-05-26 11:14:17 +0000372 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000373
374 # A marshalling error is going to occur because we're returning a
375 # complex number
Serhiy Storchakadba90392016-05-10 12:01:23 +0300376 def add(x, y):
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000377 return x+y+0j
378
379 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000380 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000381 server.register_function(add, 'add')
382
383 server.serve_forever()
384
385The client code for the preceding server::
386
Georg Brandl38eceaa2008-05-26 11:14:17 +0000387 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000388
Georg Brandl38eceaa2008-05-26 11:14:17 +0000389 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000390 try:
391 proxy.add(2, 5)
Georg Brandl0dedf452009-05-22 16:44:06 +0000392 except xmlrpc.client.Fault as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000393 print("A fault occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000394 print("Fault code: %d" % err.faultCode)
395 print("Fault string: %s" % err.faultString)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000396
397
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399.. _protocol-error-objects:
400
401ProtocolError Objects
402---------------------
403
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300404.. class:: ProtocolError
405
406 A :class:`ProtocolError` object describes a protocol error in the underlying
407 transport layer (such as a 404 'not found' error if the server named by the URI
408 does not exist). It has the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300411 .. attribute:: url
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300413 The URI or URL that triggered the error.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300416 .. attribute:: errcode
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300418 The error code.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300421 .. attribute:: errmsg
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300423 The error message or diagnostic string.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300426 .. attribute:: headers
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Serhiy Storchakada7880a2016-05-07 08:44:15 +0300428 A dict containing the headers of the HTTP/HTTPS request that triggered the
429 error.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000431In the following example we're going to intentionally cause a :exc:`ProtocolError`
432by providing an invalid URI::
433
Georg Brandl38eceaa2008-05-26 11:14:17 +0000434 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000435
Martin Panter6245cb32016-04-15 02:14:19 +0000436 # create a ServerProxy with a URI that doesn't respond to XMLRPC requests
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000437 proxy = xmlrpc.client.ServerProxy("http://google.com/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000438
439 try:
440 proxy.some_method()
Georg Brandl0dedf452009-05-22 16:44:06 +0000441 except xmlrpc.client.ProtocolError as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000442 print("A protocol error occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000443 print("URL: %s" % err.url)
444 print("HTTP/HTTPS headers: %s" % err.headers)
445 print("Error code: %d" % err.errcode)
446 print("Error message: %s" % err.errmsg)
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448MultiCall Objects
449-----------------
450
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200451The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
452remote server into a single request [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454
455.. class:: MultiCall(server)
456
457 Create an object used to boxcar method calls. *server* is the eventual target of
458 the call. Calls can be made to the result object, but they will immediately
459 return ``None``, and only store the call name and parameters in the
460 :class:`MultiCall` object. Calling the object itself causes all stored calls to
461 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000462 is a :term:`generator`; iterating over this generator yields the individual
463 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400465A usage example of this class follows. The server code::
Georg Brandl116aa622007-08-15 14:28:22 +0000466
Georg Brandl38eceaa2008-05-26 11:14:17 +0000467 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000468
Ezio Melotti79016e12013-08-08 15:45:56 +0300469 def add(x, y):
470 return x + y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000471
472 def subtract(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300473 return x - y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000474
475 def multiply(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300476 return x * y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000477
478 def divide(x, y):
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400479 return x // y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000480
481 # A simple server with simple arithmetic functions
482 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000483 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000484 server.register_multicall_functions()
485 server.register_function(add, 'add')
486 server.register_function(subtract, 'subtract')
487 server.register_function(multiply, 'multiply')
488 server.register_function(divide, 'divide')
489 server.serve_forever()
490
491The client code for the preceding server::
492
Georg Brandl38eceaa2008-05-26 11:14:17 +0000493 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000494
Georg Brandl38eceaa2008-05-26 11:14:17 +0000495 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
496 multicall = xmlrpc.client.MultiCall(proxy)
Ezio Melotti79016e12013-08-08 15:45:56 +0300497 multicall.add(7, 3)
498 multicall.subtract(7, 3)
499 multicall.multiply(7, 3)
500 multicall.divide(7, 3)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000501 result = multicall()
502
Ezio Melotti79016e12013-08-08 15:45:56 +0300503 print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505
506Convenience Functions
507---------------------
508
Georg Brandl7f01a132009-09-16 15:58:14 +0000509.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
512 is true. *params* can be either a tuple of arguments or an instance of the
513 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
514 can be returned, meaning that *params* must be of length 1. *encoding*, if
515 supplied, is the encoding to use in the generated XML; the default is UTF-8.
516 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
517 it via an extension, provide a true value for *allow_none*.
518
519
Florent Xicluna61665192011-11-15 20:53:25 +0100520.. function:: loads(data, use_datetime=False, use_builtin_types=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522 Convert an XML-RPC request or response into Python objects, a ``(params,
523 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
524 ``None`` if no method name is present in the packet. If the XML-RPC packet
525 represents a fault condition, this function will raise a :exc:`Fault` exception.
Florent Xicluna61665192011-11-15 20:53:25 +0100526 The *use_builtin_types* flag can be used to cause date/time values to be
527 presented as :class:`datetime.datetime` objects and binary data to be
528 presented as :class:`bytes` objects; this flag is false by default.
529
530 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
531 applies only to date/time values.
532
533 .. versionchanged:: 3.3
534 The *use_builtin_types* flag was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537.. _xmlrpc-client-example:
538
539Example of Client Usage
540-----------------------
541
542::
543
544 # simple test program (from the XML-RPC specification)
Georg Brandl38eceaa2008-05-26 11:14:17 +0000545 from xmlrpc.client import ServerProxy, Error
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547 # server = ServerProxy("http://localhost:8000") # local server
Brett Cannon33a40002014-03-21 11:24:40 -0400548 with ServerProxy("http://betty.userland.com") as proxy:
Georg Brandl116aa622007-08-15 14:28:22 +0000549
Brett Cannon33a40002014-03-21 11:24:40 -0400550 print(proxy)
Georg Brandl116aa622007-08-15 14:28:22 +0000551
Brett Cannon33a40002014-03-21 11:24:40 -0400552 try:
553 print(proxy.examples.getStateName(41))
554 except Error as v:
555 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000556
Martin Panter1c5e7152016-02-22 09:04:22 +0000557To access an XML-RPC server through a HTTP proxy, you need to define a custom
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000558transport. The following example shows how:
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000560.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562::
563
Georg Brandl24420152008-05-26 16:32:26 +0000564 import xmlrpc.client, http.client
Georg Brandl116aa622007-08-15 14:28:22 +0000565
Georg Brandl38eceaa2008-05-26 11:14:17 +0000566 class ProxiedTransport(xmlrpc.client.Transport):
Georg Brandl116aa622007-08-15 14:28:22 +0000567 def set_proxy(self, proxy):
568 self.proxy = proxy
Serhiy Storchakadba90392016-05-10 12:01:23 +0300569
Georg Brandl116aa622007-08-15 14:28:22 +0000570 def make_connection(self, host):
571 self.realhost = host
Martin Panter1c5e7152016-02-22 09:04:22 +0000572 h = http.client.HTTPConnection(self.proxy)
Georg Brandl06788c92009-01-03 21:31:47 +0000573 return h
Serhiy Storchakadba90392016-05-10 12:01:23 +0300574
Martin Panter1c5e7152016-02-22 09:04:22 +0000575 def send_request(self, connection, handler, request_body, debug):
Georg Brandl116aa622007-08-15 14:28:22 +0000576 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
Serhiy Storchakadba90392016-05-10 12:01:23 +0300577
Georg Brandl116aa622007-08-15 14:28:22 +0000578 def send_host(self, connection, host):
579 connection.putheader('Host', self.realhost)
580
581 p = ProxiedTransport()
582 p.set_proxy('proxy-server:8080')
Martin Panter1c5e7152016-02-22 09:04:22 +0000583 server = xmlrpc.client.ServerProxy('http://time.xmlrpc.com/RPC2', transport=p)
Collin Winterc79461b2007-09-01 23:34:30 +0000584 print(server.currentTime.getCurrentTime())
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000586
587Example of Client and Server Usage
588----------------------------------
589
590See :ref:`simplexmlrpcserver-example`.
591
592
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200593.. rubric:: Footnotes
594
595.. [#] This approach has been first presented in `a discussion on xmlrpc.com
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300596 <https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200597.. the link now points to webarchive since the one at
598.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
599.. doesn't reply)