1:mod:`xmlrpc.client` --- XML-RPC client access
2==============================================
3
4.. module:: xmlrpc.client
5   :synopsis: XML-RPC client access.
6
7.. moduleauthor:: Fredrik Lundh <[email protected]>
8.. sectionauthor:: Eric S. Raymond <[email protected]>
9
10**Source code:** :source:`Lib/xmlrpc/client.py`
11
12.. XXX Not everything is documented yet.  It might be good to describe
13   Marshaller, Unmarshaller, getparser and Transport.
14
15--------------
16
17XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) 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
24.. 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
30.. versionchanged:: 3.5
31
32   For HTTPS URIs, :mod:`xmlrpc.client` now performs all the necessary
33   certificate and hostname checks by default.
34
35.. include:: ../includes/wasm-notavail.rst
36
37.. class:: ServerProxy(uri, transport=None, encoding=None, verbose=False, \
38                       allow_none=False, use_datetime=False, \
39                       use_builtin_types=False, *, headers=(), context=None)
40
41   A :class:`ServerProxy` instance is an object that manages communication with a
42   remote XML-RPC server.  The required first argument is a URI (Uniform Resource
43   Indicator), and will normally be the URL of the server.  The optional second
44   argument is a transport factory instance; by default it is an internal
45   :class:`SafeTransport` instance for https: URLs and an internal HTTP
46   :class:`Transport` instance otherwise.  The optional third argument is an
47   encoding, by default UTF-8. The optional fourth argument is a debugging flag.
48
49   The following parameters govern the use of the returned proxy instance.
50   If *allow_none* is true,  the Python constant ``None`` will be translated into
51   XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
52   a commonly used extension to the XML-RPC specification, but isn't supported by
53   all clients and servers; see `http://ontosys.com/xml-rpc/extensions.php
54   <https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php>`_
55   for a description.
56   The *use_builtin_types* flag can be used to cause date/time values
57   to be presented as :class:`datetime.datetime` objects and binary data to be
58   presented as :class:`bytes` objects; this flag is false by default.
59   :class:`datetime.datetime`, :class:`bytes` and :class:`bytearray` objects
60   may be passed to calls.
61   The *headers* parameter is an optional sequence of HTTP headers to send with
62   each request, expressed as a sequence of 2-tuples representing the header
63   name and value. (e.g. ``[('Header-Name', 'value')]``).
64   The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
65   applies only to date/time values.
66
67.. versionchanged:: 3.3
68    The *use_builtin_types* flag was added.
69
70.. versionchanged:: 3.8
71    The *headers* parameter was added.
72
73   Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
74   Basic Authentication: ``http://user:pass@host:port/path``.  The  ``user:pass``
75   portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
76   the remote server as part of the connection process when invoking an XML-RPC
77   method.  You only need to use this if the remote server requires a Basic
78   Authentication user and password. If an HTTPS URL is provided, *context* may
79   be :class:`ssl.SSLContext` and configures the SSL settings of the underlying
80   HTTPS connection.
81
82   The returned instance is a proxy object with methods that can be used to invoke
83   corresponding RPC calls on the remote server.  If the remote server supports the
84   introspection API, the proxy can also be used to query the remote server for the
85   methods it supports (service discovery) and fetch other server-associated
86   metadata.
87
88   Types that are conformable (e.g. that can be marshalled through XML),
89   include the following (and except where noted, they are unmarshalled
90   as the same Python type):
91
92   .. tabularcolumns:: |l|L|
93
94   +----------------------+-------------------------------------------------------+
95   | XML-RPC type         | Python type                                           |
96   +======================+=======================================================+
97   | ``boolean``          | :class:`bool`                                         |
98   +----------------------+-------------------------------------------------------+
99   | ``int``, ``i1``,     | :class:`int` in range from -2147483648 to 2147483647. |
100   | ``i2``,  ``i4``,     | Values get the ``<int>`` tag.                         |
101   | ``i8`` or            |                                                       |
102   | ``biginteger``       |                                                       |
103   +----------------------+-------------------------------------------------------+
104   | ``double`` or        | :class:`float`.  Values get the ``<double>`` tag.     |
105   | ``float``            |                                                       |
106   +----------------------+-------------------------------------------------------+
107   | ``string``           | :class:`str`                                          |
108   +----------------------+-------------------------------------------------------+
109   | ``array``            | :class:`list` or :class:`tuple` containing            |
110   |                      | conformable elements.  Arrays are returned as         |
111   |                      | :class:`lists <list>`.                                |
112   +----------------------+-------------------------------------------------------+
113   | ``struct``           | :class:`dict`.  Keys must be strings, values may be   |
114   |                      | any conformable type.  Objects of user-defined        |
115   |                      | classes can be passed in; only their                  |
116   |                      | :attr:`~object.__dict__` attribute is transmitted.    |
117   +----------------------+-------------------------------------------------------+
118   | ``dateTime.iso8601`` | :class:`DateTime` or :class:`datetime.datetime`.      |
119   |                      | Returned type depends on values of                    |
120   |                      | *use_builtin_types* and *use_datetime* flags.         |
121   +----------------------+-------------------------------------------------------+
122   | ``base64``           | :class:`Binary`, :class:`bytes` or                    |
123   |                      | :class:`bytearray`.  Returned type depends on the     |
124   |                      | value of the *use_builtin_types* flag.                |
125   +----------------------+-------------------------------------------------------+
126   | ``nil``              | The ``None`` constant.  Passing is allowed only if    |
127   |                      | *allow_none* is true.                                 |
128   +----------------------+-------------------------------------------------------+
129   | ``bigdecimal``       | :class:`decimal.Decimal`.  Returned type only.        |
130   +----------------------+-------------------------------------------------------+
131
132   This is the full set of data types supported by XML-RPC.  Method calls may also
133   raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
134   :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
135   Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
136   :exc:`Error`.  Note that the xmlrpc client module currently does not marshal
137   instances of subclasses of built-in types.
138
139   When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
140   will be automatically escaped.  However, it's the caller's responsibility to
141   ensure that the string is free of characters that aren't allowed in XML, such as
142   the control characters with ASCII values between 0 and 31 (except, of course,
143   tab, newline and carriage return); failing to do this will result in an XML-RPC
144   request that isn't well-formed XML.  If you have to pass arbitrary bytes
145   via XML-RPC, use :class:`bytes` or :class:`bytearray` classes or the
146   :class:`Binary` wrapper class described below.
147
148   :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
149   compatibility.  New code should use :class:`ServerProxy`.
150
151   .. versionchanged:: 3.5
152      Added the *context* argument.
153
154   .. versionchanged:: 3.6
155      Added support of type tags with prefixes (e.g. ``ex:nil``).
156      Added support of unmarshalling additional types used by Apache XML-RPC
157      implementation for numerics: ``i1``, ``i2``, ``i8``, ``biginteger``,
158      ``float`` and ``bigdecimal``.
159      See https://ws.apache.org/xmlrpc/types.html for a description.
160
161
162.. seealso::
163
164   `XML-RPC HOWTO <https://tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
165      A good description of XML-RPC operation and client software in several languages.
166      Contains pretty much everything an XML-RPC client developer needs to know.
167
168   `XML-RPC Introspection <https://xmlrpc-c.sourceforge.net/introspection.html>`_
169      Describes the XML-RPC protocol extension for introspection.
170
171   `XML-RPC Specification <http://xmlrpc.scripting.com/spec.html>`_
172      The official specification.
173
174.. _serverproxy-objects:
175
176ServerProxy Objects
177-------------------
178
179A :class:`ServerProxy` instance has a method corresponding to each remote
180procedure call accepted by the XML-RPC server.  Calling the method performs an
181RPC, dispatched by both name and argument signature (e.g. the same method name
182can be overloaded with multiple argument signatures).  The RPC finishes by
183returning a value, which may be either returned data in a conformant type or a
184:class:`Fault` or :class:`ProtocolError` object indicating an error.
185
186Servers that support the XML introspection API support some common methods
187grouped under the reserved :attr:`~ServerProxy.system` attribute:
188
189
190.. method:: ServerProxy.system.listMethods()
191
192   This method returns a list of strings, one for each (non-system) method
193   supported by the XML-RPC server.
194
195
196.. method:: ServerProxy.system.methodSignature(name)
197
198   This method takes one parameter, the name of a method implemented by the XML-RPC
199   server. It returns an array of possible signatures for this method. A signature
200   is an array of types. The first of these types is the return type of the method,
201   the rest are parameters.
202
203   Because multiple signatures (ie. overloading) is permitted, this method returns
204   a list of signatures rather than a singleton.
205
206   Signatures themselves are restricted to the top level parameters expected by a
207   method. For instance if a method expects one array of structs as a parameter,
208   and it returns a string, its signature is simply "string, array". If it expects
209   three integers and returns a string, its signature is "string, int, int, int".
210
211   If no signature is defined for the method, a non-array value is returned. In
212   Python this means that the type of the returned  value will be something other
213   than list.
214
215
216.. method:: ServerProxy.system.methodHelp(name)
217
218   This method takes one parameter, the name of a method implemented by the XML-RPC
219   server.  It returns a documentation string describing the use of that method. If
220   no such string is available, an empty string is returned. The documentation
221   string may contain HTML markup.
222
223.. versionchanged:: 3.5
224
225   Instances of :class:`ServerProxy` support the :term:`context manager` protocol
226   for closing the underlying transport.
227
228
229A working example follows. The server code::
230
231   from xmlrpc.server import SimpleXMLRPCServer
232
233   def is_even(n):
234       return n % 2 == 0
235
236   server = SimpleXMLRPCServer(("localhost", 8000))
237   print("Listening on port 8000...")
238   server.register_function(is_even, "is_even")
239   server.serve_forever()
240
241The client code for the preceding server::
242
243   import xmlrpc.client
244
245   with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
246       print("3 is even: %s" % str(proxy.is_even(3)))
247       print("100 is even: %s" % str(proxy.is_even(100)))
248
249.. _datetime-objects:
250
251DateTime Objects
252----------------
253
254.. class:: DateTime
255
256   This class may be initialized with seconds since the epoch, a time
257   tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
258   instance.  It has the following methods, supported mainly for internal
259   use by the marshalling/unmarshalling code:
260
261
262   .. method:: decode(string)
263
264      Accept a string as the instance's new time value.
265
266
267   .. method:: encode(out)
268
269      Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
270      object.
271
272   It also supports certain of Python's built-in operators through rich comparison
273   and :meth:`__repr__` methods.
274
275A working example follows. The server code::
276
277   import datetime
278   from xmlrpc.server import SimpleXMLRPCServer
279   import xmlrpc.client
280
281   def today():
282       today = datetime.datetime.today()
283       return xmlrpc.client.DateTime(today)
284
285   server = SimpleXMLRPCServer(("localhost", 8000))
286   print("Listening on port 8000...")
287   server.register_function(today, "today")
288   server.serve_forever()
289
290The client code for the preceding server::
291
292   import xmlrpc.client
293   import datetime
294
295   proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
296
297   today = proxy.today()
298   # convert the ISO8601 string to a datetime object
299   converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
300   print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
301
302.. _binary-objects:
303
304Binary Objects
305--------------
306
307.. class:: Binary
308
309   This class may be initialized from bytes data (which may include NULs). The
310   primary access to the content of a :class:`Binary` object is provided by an
311   attribute:
312
313
314   .. attribute:: data
315
316      The binary data encapsulated by the :class:`Binary` instance.  The data is
317      provided as a :class:`bytes` object.
318
319   :class:`Binary` objects have the following methods, supported mainly for
320   internal use by the marshalling/unmarshalling code:
321
322
323   .. method:: decode(bytes)
324
325      Accept a base64 :class:`bytes` object and decode it as the instance's new data.
326
327
328   .. method:: encode(out)
329
330      Write the XML-RPC base 64 encoding of this binary item to the *out* stream object.
331
332      The encoded data will have newlines every 76 characters as per
333      :rfc:`RFC 2045 section 6.8 <2045#section-6.8>`,
334      which was the de facto standard base64 specification when the
335      XML-RPC spec was written.
336
337   It also supports certain of Python's built-in operators through :meth:`__eq__`
338   and :meth:`__ne__` methods.
339
340Example usage of the binary objects.  We're going to transfer an image over
341XMLRPC::
342
343   from xmlrpc.server import SimpleXMLRPCServer
344   import xmlrpc.client
345
346   def python_logo():
347       with open("python_logo.jpg", "rb") as handle:
348           return xmlrpc.client.Binary(handle.read())
349
350   server = SimpleXMLRPCServer(("localhost", 8000))
351   print("Listening on port 8000...")
352   server.register_function(python_logo, 'python_logo')
353
354   server.serve_forever()
355
356The client gets the image and saves it to a file::
357
358   import xmlrpc.client
359
360   proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
361   with open("fetched_python_logo.jpg", "wb") as handle:
362       handle.write(proxy.python_logo().data)
363
364.. _fault-objects:
365
366Fault Objects
367-------------
368
369.. class:: Fault
370
371   A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
372   objects have the following attributes:
373
374
375   .. attribute:: faultCode
376
377      An int indicating the fault type.
378
379
380   .. attribute:: faultString
381
382      A string containing a diagnostic message associated with the fault.
383
384In the following example we're going to intentionally cause a :exc:`Fault` by
385returning a complex type object.  The server code::
386
387   from xmlrpc.server import SimpleXMLRPCServer
388
389   # A marshalling error is going to occur because we're returning a
390   # complex number
391   def add(x, y):
392       return x+y+0j
393
394   server = SimpleXMLRPCServer(("localhost", 8000))
395   print("Listening on port 8000...")
396   server.register_function(add, 'add')
397
398   server.serve_forever()
399
400The client code for the preceding server::
401
402   import xmlrpc.client
403
404   proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
405   try:
406       proxy.add(2, 5)
407   except xmlrpc.client.Fault as err:
408       print("A fault occurred")
409       print("Fault code: %d" % err.faultCode)
410       print("Fault string: %s" % err.faultString)
411
412
413
414.. _protocol-error-objects:
415
416ProtocolError Objects
417---------------------
418
419.. class:: ProtocolError
420
421   A :class:`ProtocolError` object describes a protocol error in the underlying
422   transport layer (such as a 404 'not found' error if the server named by the URI
423   does not exist).  It has the following attributes:
424
425
426   .. attribute:: url
427
428      The URI or URL that triggered the error.
429
430
431   .. attribute:: errcode
432
433      The error code.
434
435
436   .. attribute:: errmsg
437
438      The error message or diagnostic string.
439
440
441   .. attribute:: headers
442
443      A dict containing the headers of the HTTP/HTTPS request that triggered the
444      error.
445
446In the following example we're going to intentionally cause a :exc:`ProtocolError`
447by providing an invalid URI::
448
449   import xmlrpc.client
450
451   # create a ServerProxy with a URI that doesn't respond to XMLRPC requests
452   proxy = xmlrpc.client.ServerProxy("http://google.com/")
453
454   try:
455       proxy.some_method()
456   except xmlrpc.client.ProtocolError as err:
457       print("A protocol error occurred")
458       print("URL: %s" % err.url)
459       print("HTTP/HTTPS headers: %s" % err.headers)
460       print("Error code: %d" % err.errcode)
461       print("Error message: %s" % err.errmsg)
462
463MultiCall Objects
464-----------------
465
466The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
467remote server into a single request [#]_.
468
469
470.. class:: MultiCall(server)
471
472   Create an object used to boxcar method calls. *server* is the eventual target of
473   the call. Calls can be made to the result object, but they will immediately
474   return ``None``, and only store the call name and parameters in the
475   :class:`MultiCall` object. Calling the object itself causes all stored calls to
476   be transmitted as a single ``system.multicall`` request. The result of this call
477   is a :term:`generator`; iterating over this generator yields the individual
478   results.
479
480A usage example of this class follows.  The server code::
481
482   from xmlrpc.server import SimpleXMLRPCServer
483
484   def add(x, y):
485       return x + y
486
487   def subtract(x, y):
488       return x - y
489
490   def multiply(x, y):
491       return x * y
492
493   def divide(x, y):
494       return x // y
495
496   # A simple server with simple arithmetic functions
497   server = SimpleXMLRPCServer(("localhost", 8000))
498   print("Listening on port 8000...")
499   server.register_multicall_functions()
500   server.register_function(add, 'add')
501   server.register_function(subtract, 'subtract')
502   server.register_function(multiply, 'multiply')
503   server.register_function(divide, 'divide')
504   server.serve_forever()
505
506The client code for the preceding server::
507
508   import xmlrpc.client
509
510   proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
511   multicall = xmlrpc.client.MultiCall(proxy)
512   multicall.add(7, 3)
513   multicall.subtract(7, 3)
514   multicall.multiply(7, 3)
515   multicall.divide(7, 3)
516   result = multicall()
517
518   print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
519
520
521Convenience Functions
522---------------------
523
524.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
525
526   Convert *params* into an XML-RPC request. or into a response if *methodresponse*
527   is true. *params* can be either a tuple of arguments or an instance of the
528   :exc:`Fault` exception class.  If *methodresponse* is true, only a single value
529   can be returned, meaning that *params* must be of length 1. *encoding*, if
530   supplied, is the encoding to use in the generated XML; the default is UTF-8.
531   Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
532   it via an extension,  provide a true value for *allow_none*.
533
534
535.. function:: loads(data, use_datetime=False, use_builtin_types=False)
536
537   Convert an XML-RPC request or response into Python objects, a ``(params,
538   methodname)``.  *params* is a tuple of argument; *methodname* is a string, or
539   ``None`` if no method name is present in the packet. If the XML-RPC packet
540   represents a fault condition, this function will raise a :exc:`Fault` exception.
541   The *use_builtin_types* flag can be used to cause date/time values to be
542   presented as :class:`datetime.datetime` objects and binary data to be
543   presented as :class:`bytes` objects; this flag is false by default.
544
545   The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
546   applies only to date/time values.
547
548   .. versionchanged:: 3.3
549      The *use_builtin_types* flag was added.
550
551
552.. _xmlrpc-client-example:
553
554Example of Client Usage
555-----------------------
556
557::
558
559   # simple test program (from the XML-RPC specification)
560   from xmlrpc.client import ServerProxy, Error
561
562   # server = ServerProxy("http://localhost:8000") # local server
563   with ServerProxy("http://betty.userland.com") as proxy:
564
565       print(proxy)
566
567       try:
568           print(proxy.examples.getStateName(41))
569       except Error as v:
570           print("ERROR", v)
571
572To access an XML-RPC server through a HTTP proxy, you need to define a custom
573transport.  The following example shows how::
574
575   import http.client
576   import xmlrpc.client
577
578   class ProxiedTransport(xmlrpc.client.Transport):
579
580       def set_proxy(self, host, port=None, headers=None):
581           self.proxy = host, port
582           self.proxy_headers = headers
583
584       def make_connection(self, host):
585           connection = http.client.HTTPConnection(*self.proxy)
586           connection.set_tunnel(host, headers=self.proxy_headers)
587           self._connection = host, connection
588           return connection
589
590   transport = ProxiedTransport()
591   transport.set_proxy('proxy-server', 8080)
592   server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
593   print(server.examples.getStateName(41))
594
595
596Example of Client and Server Usage
597----------------------------------
598
599See :ref:`simplexmlrpcserver-example`.
600
601
602.. rubric:: Footnotes
603
604.. [#] This approach has been first presented in `a discussion on xmlrpc.com
605   <https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
606.. the link now points to webarchive since the one at
607.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
608.. doesn't reply)
609