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 <fredrik@pythonware.com> 8.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com> 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.io/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 273 :meth:`rich comparison <object.__lt__>` and :meth:`~object.__repr__` 274 methods. 275 276A working example follows. The server code:: 277 278 import datetime 279 from xmlrpc.server import SimpleXMLRPCServer 280 import xmlrpc.client 281 282 def today(): 283 today = datetime.datetime.today() 284 return xmlrpc.client.DateTime(today) 285 286 server = SimpleXMLRPCServer(("localhost", 8000)) 287 print("Listening on port 8000...") 288 server.register_function(today, "today") 289 server.serve_forever() 290 291The client code for the preceding server:: 292 293 import xmlrpc.client 294 import datetime 295 296 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") 297 298 today = proxy.today() 299 # convert the ISO8601 string to a datetime object 300 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S") 301 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")) 302 303.. _binary-objects: 304 305Binary Objects 306-------------- 307 308.. class:: Binary 309 310 This class may be initialized from bytes data (which may include NULs). The 311 primary access to the content of a :class:`Binary` object is provided by an 312 attribute: 313 314 315 .. attribute:: data 316 317 The binary data encapsulated by the :class:`Binary` instance. The data is 318 provided as a :class:`bytes` object. 319 320 :class:`Binary` objects have the following methods, supported mainly for 321 internal use by the marshalling/unmarshalling code: 322 323 324 .. method:: decode(bytes) 325 326 Accept a base64 :class:`bytes` object and decode it as the instance's new data. 327 328 329 .. method:: encode(out) 330 331 Write the XML-RPC base 64 encoding of this binary item to the *out* stream object. 332 333 The encoded data will have newlines every 76 characters as per 334 :rfc:`RFC 2045 section 6.8 <2045#section-6.8>`, 335 which was the de facto standard base64 specification when the 336 XML-RPC spec was written. 337 338 It also supports certain of Python's built-in operators through 339 :meth:`~object.__eq__` and :meth:`~object.__ne__` methods. 340 341Example usage of the binary objects. We're going to transfer an image over 342XMLRPC:: 343 344 from xmlrpc.server import SimpleXMLRPCServer 345 import xmlrpc.client 346 347 def python_logo(): 348 with open("python_logo.jpg", "rb") as handle: 349 return xmlrpc.client.Binary(handle.read()) 350 351 server = SimpleXMLRPCServer(("localhost", 8000)) 352 print("Listening on port 8000...") 353 server.register_function(python_logo, 'python_logo') 354 355 server.serve_forever() 356 357The client gets the image and saves it to a file:: 358 359 import xmlrpc.client 360 361 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") 362 with open("fetched_python_logo.jpg", "wb") as handle: 363 handle.write(proxy.python_logo().data) 364 365.. _fault-objects: 366 367Fault Objects 368------------- 369 370.. class:: Fault 371 372 A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault 373 objects have the following attributes: 374 375 376 .. attribute:: faultCode 377 378 An int indicating the fault type. 379 380 381 .. attribute:: faultString 382 383 A string containing a diagnostic message associated with the fault. 384 385In the following example we're going to intentionally cause a :exc:`Fault` by 386returning a complex type object. The server code:: 387 388 from xmlrpc.server import SimpleXMLRPCServer 389 390 # A marshalling error is going to occur because we're returning a 391 # complex number 392 def add(x, y): 393 return x+y+0j 394 395 server = SimpleXMLRPCServer(("localhost", 8000)) 396 print("Listening on port 8000...") 397 server.register_function(add, 'add') 398 399 server.serve_forever() 400 401The client code for the preceding server:: 402 403 import xmlrpc.client 404 405 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") 406 try: 407 proxy.add(2, 5) 408 except xmlrpc.client.Fault as err: 409 print("A fault occurred") 410 print("Fault code: %d" % err.faultCode) 411 print("Fault string: %s" % err.faultString) 412 413 414 415.. _protocol-error-objects: 416 417ProtocolError Objects 418--------------------- 419 420.. class:: ProtocolError 421 422 A :class:`ProtocolError` object describes a protocol error in the underlying 423 transport layer (such as a 404 'not found' error if the server named by the URI 424 does not exist). It has the following attributes: 425 426 427 .. attribute:: url 428 429 The URI or URL that triggered the error. 430 431 432 .. attribute:: errcode 433 434 The error code. 435 436 437 .. attribute:: errmsg 438 439 The error message or diagnostic string. 440 441 442 .. attribute:: headers 443 444 A dict containing the headers of the HTTP/HTTPS request that triggered the 445 error. 446 447In the following example we're going to intentionally cause a :exc:`ProtocolError` 448by providing an invalid URI:: 449 450 import xmlrpc.client 451 452 # create a ServerProxy with a URI that doesn't respond to XMLRPC requests 453 proxy = xmlrpc.client.ServerProxy("http://google.com/") 454 455 try: 456 proxy.some_method() 457 except xmlrpc.client.ProtocolError as err: 458 print("A protocol error occurred") 459 print("URL: %s" % err.url) 460 print("HTTP/HTTPS headers: %s" % err.headers) 461 print("Error code: %d" % err.errcode) 462 print("Error message: %s" % err.errmsg) 463 464MultiCall Objects 465----------------- 466 467The :class:`MultiCall` object provides a way to encapsulate multiple calls to a 468remote server into a single request [#]_. 469 470 471.. class:: MultiCall(server) 472 473 Create an object used to boxcar method calls. *server* is the eventual target of 474 the call. Calls can be made to the result object, but they will immediately 475 return ``None``, and only store the call name and parameters in the 476 :class:`MultiCall` object. Calling the object itself causes all stored calls to 477 be transmitted as a single ``system.multicall`` request. The result of this call 478 is a :term:`generator`; iterating over this generator yields the individual 479 results. 480 481A usage example of this class follows. The server code:: 482 483 from xmlrpc.server import SimpleXMLRPCServer 484 485 def add(x, y): 486 return x + y 487 488 def subtract(x, y): 489 return x - y 490 491 def multiply(x, y): 492 return x * y 493 494 def divide(x, y): 495 return x // y 496 497 # A simple server with simple arithmetic functions 498 server = SimpleXMLRPCServer(("localhost", 8000)) 499 print("Listening on port 8000...") 500 server.register_multicall_functions() 501 server.register_function(add, 'add') 502 server.register_function(subtract, 'subtract') 503 server.register_function(multiply, 'multiply') 504 server.register_function(divide, 'divide') 505 server.serve_forever() 506 507The client code for the preceding server:: 508 509 import xmlrpc.client 510 511 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") 512 multicall = xmlrpc.client.MultiCall(proxy) 513 multicall.add(7, 3) 514 multicall.subtract(7, 3) 515 multicall.multiply(7, 3) 516 multicall.divide(7, 3) 517 result = multicall() 518 519 print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result)) 520 521 522Convenience Functions 523--------------------- 524 525.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False) 526 527 Convert *params* into an XML-RPC request. or into a response if *methodresponse* 528 is true. *params* can be either a tuple of arguments or an instance of the 529 :exc:`Fault` exception class. If *methodresponse* is true, only a single value 530 can be returned, meaning that *params* must be of length 1. *encoding*, if 531 supplied, is the encoding to use in the generated XML; the default is UTF-8. 532 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using 533 it via an extension, provide a true value for *allow_none*. 534 535 536.. function:: loads(data, use_datetime=False, use_builtin_types=False) 537 538 Convert an XML-RPC request or response into Python objects, a ``(params, 539 methodname)``. *params* is a tuple of argument; *methodname* is a string, or 540 ``None`` if no method name is present in the packet. If the XML-RPC packet 541 represents a fault condition, this function will raise a :exc:`Fault` exception. 542 The *use_builtin_types* flag can be used to cause date/time values to be 543 presented as :class:`datetime.datetime` objects and binary data to be 544 presented as :class:`bytes` objects; this flag is false by default. 545 546 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it 547 applies only to date/time values. 548 549 .. versionchanged:: 3.3 550 The *use_builtin_types* flag was added. 551 552 553.. _xmlrpc-client-example: 554 555Example of Client Usage 556----------------------- 557 558:: 559 560 # simple test program (from the XML-RPC specification) 561 from xmlrpc.client import ServerProxy, Error 562 563 # server = ServerProxy("http://localhost:8000") # local server 564 with ServerProxy("http://betty.userland.com") as proxy: 565 566 print(proxy) 567 568 try: 569 print(proxy.examples.getStateName(41)) 570 except Error as v: 571 print("ERROR", v) 572 573To access an XML-RPC server through a HTTP proxy, you need to define a custom 574transport. The following example shows how:: 575 576 import http.client 577 import xmlrpc.client 578 579 class ProxiedTransport(xmlrpc.client.Transport): 580 581 def set_proxy(self, host, port=None, headers=None): 582 self.proxy = host, port 583 self.proxy_headers = headers 584 585 def make_connection(self, host): 586 connection = http.client.HTTPConnection(*self.proxy) 587 connection.set_tunnel(host, headers=self.proxy_headers) 588 self._connection = host, connection 589 return connection 590 591 transport = ProxiedTransport() 592 transport.set_proxy('proxy-server', 8080) 593 server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport) 594 print(server.examples.getStateName(41)) 595 596 597Example of Client and Server Usage 598---------------------------------- 599 600See :ref:`simplexmlrpcserver-example`. 601 602 603.. rubric:: Footnotes 604 605.. [#] This approach has been first presented in `a discussion on xmlrpc.com 606 <https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_. 607.. the link now points to webarchive since the one at 608.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin 609.. doesn't reply) 610