blob: 3cb19d186267b1593f3483b200b24d1f8d945d86 [file] [log] [blame]
Georg Brandl38eceaa2008-05-26 11:14:17 +00001:mod:`xmlrpc.client` --- XML-RPC client access
2==============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Georg Brandl38eceaa2008-05-26 11:14:17 +00004.. module:: xmlrpc.client
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: XML-RPC client access.
6.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
7.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
8
9
Christian Heimes5b5e81c2007-12-31 16:14:33 +000010.. XXX Not everything is documented yet. It might be good to describe
Florent Xicluna61665192011-11-15 20:53:25 +010011 Marshaller, Unmarshaller, getparser and Transport.
Georg Brandl116aa622007-08-15 14:28:22 +000012
Raymond Hettinger3029aff2011-02-10 08:09:36 +000013**Source code:** :source:`Lib/xmlrpc/client.py`
14
15--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +000017XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
18transport. With it, a client can call methods with parameters on a remote
19server (the server is named by a URI) and get back structured data. This module
20supports writing XML-RPC client code; it handles all the details of translating
21between conformable Python objects and XML on the wire.
22
23
Christian Heimes7380a672013-03-26 17:35:55 +010024.. warning::
25
26 The :mod:`xmlrpc.client` module is not secure against maliciously
27 constructed data. If you need to parse untrusted or unauthenticated data see
28 :ref:`xml-vulnerabilities`.
29
30
Florent Xicluna61665192011-11-15 20:53:25 +010031.. class:: ServerProxy(uri, transport=None, encoding=None, verbose=False, \
32 allow_none=False, use_datetime=False, \
33 use_builtin_types=False)
34
35 .. versionchanged:: 3.3
36 The *use_builtin_types* flag was added.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38 A :class:`ServerProxy` instance is an object that manages communication with a
39 remote XML-RPC server. The required first argument is a URI (Uniform Resource
40 Indicator), and will normally be the URL of the server. The optional second
41 argument is a transport factory instance; by default it is an internal
42 :class:`SafeTransport` instance for https: URLs and an internal HTTP
43 :class:`Transport` instance otherwise. The optional third argument is an
44 encoding, by default UTF-8. The optional fourth argument is a debugging flag.
45 If *allow_none* is true, the Python constant ``None`` will be translated into
46 XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
47 a commonly-used extension to the XML-RPC specification, but isn't supported by
48 all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
Florent Xicluna61665192011-11-15 20:53:25 +010049 description. The *use_builtin_types* flag can be used to cause date/time values
50 to be presented as :class:`datetime.datetime` objects and binary data to be
51 presented as :class:`bytes` objects; this flag is false by default.
52 :class:`datetime.datetime` and :class:`bytes` objects may be passed to calls.
53
54 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
55 applies only to date/time values.
Georg Brandl116aa622007-08-15 14:28:22 +000056
57 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
58 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
59 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
60 the remote server as part of the connection process when invoking an XML-RPC
61 method. You only need to use this if the remote server requires a Basic
62 Authentication user and password.
63
64 The returned instance is a proxy object with methods that can be used to invoke
65 corresponding RPC calls on the remote server. If the remote server supports the
66 introspection API, the proxy can also be used to query the remote server for the
67 methods it supports (service discovery) and fetch other server-associated
68 metadata.
69
70 :class:`ServerProxy` instance methods take Python basic types and objects as
71 arguments and return Python basic types and classes. Types that are conformable
72 (e.g. that can be marshalled through XML), include the following (and except
73 where noted, they are unmarshalled as the same Python type):
74
Georg Brandl44ea77b2013-03-28 13:28:44 +010075 .. tabularcolumns:: |l|L|
76
Georg Brandl116aa622007-08-15 14:28:22 +000077 +---------------------------------+---------------------------------------------+
78 | Name | Meaning |
79 +=================================+=============================================+
80 | :const:`boolean` | The :const:`True` and :const:`False` |
81 | | constants |
82 +---------------------------------+---------------------------------------------+
83 | :const:`integers` | Pass in directly |
84 +---------------------------------+---------------------------------------------+
85 | :const:`floating-point numbers` | Pass in directly |
86 +---------------------------------+---------------------------------------------+
87 | :const:`strings` | Pass in directly |
88 +---------------------------------+---------------------------------------------+
89 | :const:`arrays` | Any Python sequence type containing |
90 | | conformable elements. Arrays are returned |
91 | | as lists |
92 +---------------------------------+---------------------------------------------+
93 | :const:`structures` | A Python dictionary. Keys must be strings, |
94 | | values may be any conformable type. Objects |
95 | | of user-defined classes can be passed in; |
96 | | only their *__dict__* attribute is |
97 | | transmitted. |
98 +---------------------------------+---------------------------------------------+
Florent Xicluna61665192011-11-15 20:53:25 +010099 | :const:`dates` | In seconds since the epoch. Pass in an |
100 | | instance of the :class:`DateTime` class or |
Christian Heimes05e8be12008-02-23 18:30:17 +0000101 | | a :class:`datetime.datetime` instance. |
Georg Brandl116aa622007-08-15 14:28:22 +0000102 +---------------------------------+---------------------------------------------+
Florent Xicluna61665192011-11-15 20:53:25 +0100103 | :const:`binary data` | Pass in an instance of the :class:`Binary` |
104 | | wrapper class or a :class:`bytes` instance. |
Georg Brandl116aa622007-08-15 14:28:22 +0000105 +---------------------------------+---------------------------------------------+
106
107 This is the full set of data types supported by XML-RPC. Method calls may also
108 raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
109 :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
110 Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
Georg Brandl38eceaa2008-05-26 11:14:17 +0000111 :exc:`Error`. Note that the xmlrpc client module currently does not marshal
Georg Brandl22b34312009-07-26 14:54:51 +0000112 instances of subclasses of built-in types.
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
115 will be automatically escaped. However, it's the caller's responsibility to
116 ensure that the string is free of characters that aren't allowed in XML, such as
117 the control characters with ASCII values between 0 and 31 (except, of course,
118 tab, newline and carriage return); failing to do this will result in an XML-RPC
Florent Xicluna61665192011-11-15 20:53:25 +0100119 request that isn't well-formed XML. If you have to pass arbitrary bytes
120 via XML-RPC, use the :class:`bytes` class or the class:`Binary` wrapper class
121 described below.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
124 compatibility. New code should use :class:`ServerProxy`.
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127.. seealso::
128
129 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Christian Heimesa62da1d2008-01-12 19:39:10 +0000130 A good description of XML-RPC operation and client software in several languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000131 Contains pretty much everything an XML-RPC client developer needs to know.
132
Christian Heimesa62da1d2008-01-12 19:39:10 +0000133 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
134 Describes the XML-RPC protocol extension for introspection.
Georg Brandl116aa622007-08-15 14:28:22 +0000135
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000136 `XML-RPC Specification <http://www.xmlrpc.com/spec>`_
137 The official specification.
138
139 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
140 Fredrik Lundh's "unofficial errata, intended to clarify certain
141 details in the XML-RPC specification, as well as hint at
142 'best practices' to use when designing your own XML-RPC
143 implementations."
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145.. _serverproxy-objects:
146
147ServerProxy Objects
148-------------------
149
150A :class:`ServerProxy` instance has a method corresponding to each remote
151procedure call accepted by the XML-RPC server. Calling the method performs an
152RPC, dispatched by both name and argument signature (e.g. the same method name
153can be overloaded with multiple argument signatures). The RPC finishes by
154returning a value, which may be either returned data in a conformant type or a
155:class:`Fault` or :class:`ProtocolError` object indicating an error.
156
157Servers that support the XML introspection API support some common methods
Senthil Kumarana6bac952011-07-04 11:28:30 -0700158grouped under the reserved :attr:`system` attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160
161.. method:: ServerProxy.system.listMethods()
162
163 This method returns a list of strings, one for each (non-system) method
164 supported by the XML-RPC server.
165
166
167.. method:: ServerProxy.system.methodSignature(name)
168
169 This method takes one parameter, the name of a method implemented by the XML-RPC
Georg Brandl94606482009-05-04 20:46:44 +0000170 server. It returns an array of possible signatures for this method. A signature
Georg Brandl116aa622007-08-15 14:28:22 +0000171 is an array of types. The first of these types is the return type of the method,
172 the rest are parameters.
173
174 Because multiple signatures (ie. overloading) is permitted, this method returns
175 a list of signatures rather than a singleton.
176
177 Signatures themselves are restricted to the top level parameters expected by a
178 method. For instance if a method expects one array of structs as a parameter,
179 and it returns a string, its signature is simply "string, array". If it expects
180 three integers and returns a string, its signature is "string, int, int, int".
181
182 If no signature is defined for the method, a non-array value is returned. In
183 Python this means that the type of the returned value will be something other
Georg Brandl94606482009-05-04 20:46:44 +0000184 than list.
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186
187.. method:: ServerProxy.system.methodHelp(name)
188
189 This method takes one parameter, the name of a method implemented by the XML-RPC
190 server. It returns a documentation string describing the use of that method. If
191 no such string is available, an empty string is returned. The documentation
192 string may contain HTML markup.
193
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000195A working example follows. The server code::
196
Georg Brandl38eceaa2008-05-26 11:14:17 +0000197 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000198
199 def is_even(n):
200 return n%2 == 0
201
202 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000203 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000204 server.register_function(is_even, "is_even")
205 server.serve_forever()
206
207The client code for the preceding server::
208
Georg Brandl38eceaa2008-05-26 11:14:17 +0000209 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000210
Georg Brandl38eceaa2008-05-26 11:14:17 +0000211 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Georg Brandlf6945182008-02-01 11:56:49 +0000212 print("3 is even: %s" % str(proxy.is_even(3)))
213 print("100 is even: %s" % str(proxy.is_even(100)))
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215.. _datetime-objects:
216
217DateTime Objects
218----------------
219
Christian Heimes05e8be12008-02-23 18:30:17 +0000220This class may be initialized with seconds since the epoch, a time
221tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
222instance. It has the following methods, supported mainly for internal
223use by the marshalling/unmarshalling code:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225
226.. method:: DateTime.decode(string)
227
228 Accept a string as the instance's new time value.
229
230
231.. method:: DateTime.encode(out)
232
233 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
234 object.
235
Georg Brandl05f5ab72008-09-24 09:11:47 +0000236It also supports certain of Python's built-in operators through rich comparison
Georg Brandl116aa622007-08-15 14:28:22 +0000237and :meth:`__repr__` methods.
238
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000239A working example follows. The server code::
240
241 import datetime
Georg Brandl38eceaa2008-05-26 11:14:17 +0000242 from xmlrpc.server import SimpleXMLRPCServer
243 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000244
245 def today():
246 today = datetime.datetime.today()
Georg Brandl38eceaa2008-05-26 11:14:17 +0000247 return xmlrpc.client.DateTime(today)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000248
249 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000250 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000251 server.register_function(today, "today")
252 server.serve_forever()
253
254The client code for the preceding server::
255
Georg Brandl38eceaa2008-05-26 11:14:17 +0000256 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000257 import datetime
258
Georg Brandl38eceaa2008-05-26 11:14:17 +0000259 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000260
261 today = proxy.today()
262 # convert the ISO8601 string to a datetime object
263 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
Georg Brandlf6945182008-02-01 11:56:49 +0000264 print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266.. _binary-objects:
267
268Binary Objects
269--------------
270
Florent Xicluna61665192011-11-15 20:53:25 +0100271This class may be initialized from bytes data (which may include NULs). The
Georg Brandl116aa622007-08-15 14:28:22 +0000272primary access to the content of a :class:`Binary` object is provided by an
273attribute:
274
275
276.. attribute:: Binary.data
277
278 The binary data encapsulated by the :class:`Binary` instance. The data is
Florent Xicluna61665192011-11-15 20:53:25 +0100279 provided as a :class:`bytes` object.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281:class:`Binary` objects have the following methods, supported mainly for
282internal use by the marshalling/unmarshalling code:
283
284
Florent Xicluna61665192011-11-15 20:53:25 +0100285.. method:: Binary.decode(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Florent Xicluna61665192011-11-15 20:53:25 +0100287 Accept a base64 :class:`bytes` object and decode it as the instance's new data.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289
290.. method:: Binary.encode(out)
291
292 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
293
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000294 The encoded data will have newlines every 76 characters as per
295 `RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
296 which was the de facto standard base64 specification when the
297 XML-RPC spec was written.
298
Georg Brandl05f5ab72008-09-24 09:11:47 +0000299It also supports certain of Python's built-in operators through :meth:`__eq__`
300and :meth:`__ne__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000302Example usage of the binary objects. We're going to transfer an image over
303XMLRPC::
304
Georg Brandl38eceaa2008-05-26 11:14:17 +0000305 from xmlrpc.server import SimpleXMLRPCServer
306 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000307
308 def python_logo():
Victor Stinner757db832010-01-30 02:16:55 +0000309 with open("python_logo.jpg", "rb") as handle:
310 return xmlrpc.client.Binary(handle.read())
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000311
312 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000313 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000314 server.register_function(python_logo, 'python_logo')
315
316 server.serve_forever()
317
318The client gets the image and saves it to a file::
319
Georg Brandl38eceaa2008-05-26 11:14:17 +0000320 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000321
Georg Brandl38eceaa2008-05-26 11:14:17 +0000322 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
Victor Stinner757db832010-01-30 02:16:55 +0000323 with open("fetched_python_logo.jpg", "wb") as handle:
324 handle.write(proxy.python_logo().data)
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326.. _fault-objects:
327
328Fault Objects
329-------------
330
331A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
Senthil Kumarana6bac952011-07-04 11:28:30 -0700332objects have the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334
335.. attribute:: Fault.faultCode
336
337 A string indicating the fault type.
338
339
340.. attribute:: Fault.faultString
341
342 A string containing a diagnostic message associated with the fault.
343
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000344In the following example we're going to intentionally cause a :exc:`Fault` by
345returning a complex type object. The server code::
346
Georg Brandl38eceaa2008-05-26 11:14:17 +0000347 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000348
349 # A marshalling error is going to occur because we're returning a
350 # complex number
351 def add(x,y):
352 return x+y+0j
353
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(add, 'add')
357
358 server.serve_forever()
359
360The client code for the preceding server::
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/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000365 try:
366 proxy.add(2, 5)
Georg Brandl0dedf452009-05-22 16:44:06 +0000367 except xmlrpc.client.Fault as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000368 print("A fault occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000369 print("Fault code: %d" % err.faultCode)
370 print("Fault string: %s" % err.faultString)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000371
372
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374.. _protocol-error-objects:
375
376ProtocolError Objects
377---------------------
378
379A :class:`ProtocolError` object describes a protocol error in the underlying
380transport layer (such as a 404 'not found' error if the server named by the URI
Senthil Kumarana6bac952011-07-04 11:28:30 -0700381does not exist). It has the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
384.. attribute:: ProtocolError.url
385
386 The URI or URL that triggered the error.
387
388
389.. attribute:: ProtocolError.errcode
390
391 The error code.
392
393
394.. attribute:: ProtocolError.errmsg
395
396 The error message or diagnostic string.
397
398
399.. attribute:: ProtocolError.headers
400
Guido van Rossum460add42007-08-23 02:13:35 +0000401 A dict containing the headers of the HTTP/HTTPS request that triggered the
Georg Brandl116aa622007-08-15 14:28:22 +0000402 error.
403
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000404In the following example we're going to intentionally cause a :exc:`ProtocolError`
405by providing an invalid URI::
406
Georg Brandl38eceaa2008-05-26 11:14:17 +0000407 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000408
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000409 # create a ServerProxy with an URI that doesn't respond to XMLRPC requests
410 proxy = xmlrpc.client.ServerProxy("http://google.com/")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000411
412 try:
413 proxy.some_method()
Georg Brandl0dedf452009-05-22 16:44:06 +0000414 except xmlrpc.client.ProtocolError as err:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000415 print("A protocol error occurred")
Georg Brandlf6945182008-02-01 11:56:49 +0000416 print("URL: %s" % err.url)
417 print("HTTP/HTTPS headers: %s" % err.headers)
418 print("Error code: %d" % err.errcode)
419 print("Error message: %s" % err.errmsg)
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421MultiCall Objects
422-----------------
423
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200424The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
425remote server into a single request [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427
428.. class:: MultiCall(server)
429
430 Create an object used to boxcar method calls. *server* is the eventual target of
431 the call. Calls can be made to the result object, but they will immediately
432 return ``None``, and only store the call name and parameters in the
433 :class:`MultiCall` object. Calling the object itself causes all stored calls to
434 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandl9afde1c2007-11-01 20:32:30 +0000435 is a :term:`generator`; iterating over this generator yields the individual
436 results.
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400438A usage example of this class follows. The server code::
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Georg Brandl38eceaa2008-05-26 11:14:17 +0000440 from xmlrpc.server import SimpleXMLRPCServer
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000441
Ezio Melotti79016e12013-08-08 15:45:56 +0300442 def add(x, y):
443 return x + y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000444
445 def subtract(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300446 return x - y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000447
448 def multiply(x, y):
Ezio Melotti79016e12013-08-08 15:45:56 +0300449 return x * y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000450
451 def divide(x, y):
Andrew Kuchlingc3db3732013-06-20 21:33:05 -0400452 return x // y
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000453
454 # A simple server with simple arithmetic functions
455 server = SimpleXMLRPCServer(("localhost", 8000))
Georg Brandlf6945182008-02-01 11:56:49 +0000456 print("Listening on port 8000...")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000457 server.register_multicall_functions()
458 server.register_function(add, 'add')
459 server.register_function(subtract, 'subtract')
460 server.register_function(multiply, 'multiply')
461 server.register_function(divide, 'divide')
462 server.serve_forever()
463
464The client code for the preceding server::
465
Georg Brandl38eceaa2008-05-26 11:14:17 +0000466 import xmlrpc.client
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000467
Georg Brandl38eceaa2008-05-26 11:14:17 +0000468 proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
469 multicall = xmlrpc.client.MultiCall(proxy)
Ezio Melotti79016e12013-08-08 15:45:56 +0300470 multicall.add(7, 3)
471 multicall.subtract(7, 3)
472 multicall.multiply(7, 3)
473 multicall.divide(7, 3)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000474 result = multicall()
475
Ezio Melotti79016e12013-08-08 15:45:56 +0300476 print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478
479Convenience Functions
480---------------------
481
Georg Brandl7f01a132009-09-16 15:58:14 +0000482.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
485 is true. *params* can be either a tuple of arguments or an instance of the
486 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
487 can be returned, meaning that *params* must be of length 1. *encoding*, if
488 supplied, is the encoding to use in the generated XML; the default is UTF-8.
489 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
490 it via an extension, provide a true value for *allow_none*.
491
492
Florent Xicluna61665192011-11-15 20:53:25 +0100493.. function:: loads(data, use_datetime=False, use_builtin_types=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 Convert an XML-RPC request or response into Python objects, a ``(params,
496 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
497 ``None`` if no method name is present in the packet. If the XML-RPC packet
498 represents a fault condition, this function will raise a :exc:`Fault` exception.
Florent Xicluna61665192011-11-15 20:53:25 +0100499 The *use_builtin_types* flag can be used to cause date/time values to be
500 presented as :class:`datetime.datetime` objects and binary data to be
501 presented as :class:`bytes` objects; this flag is false by default.
502
503 The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
504 applies only to date/time values.
505
506 .. versionchanged:: 3.3
507 The *use_builtin_types* flag was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510.. _xmlrpc-client-example:
511
512Example of Client Usage
513-----------------------
514
515::
516
517 # simple test program (from the XML-RPC specification)
Georg Brandl38eceaa2008-05-26 11:14:17 +0000518 from xmlrpc.client import ServerProxy, Error
Georg Brandl116aa622007-08-15 14:28:22 +0000519
520 # server = ServerProxy("http://localhost:8000") # local server
521 server = ServerProxy("http://betty.userland.com")
522
Collin Winterc79461b2007-09-01 23:34:30 +0000523 print(server)
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525 try:
Collin Winterc79461b2007-09-01 23:34:30 +0000526 print(server.examples.getStateName(41))
Georg Brandl116aa622007-08-15 14:28:22 +0000527 except Error as v:
Collin Winterc79461b2007-09-01 23:34:30 +0000528 print("ERROR", v)
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530To access an XML-RPC server through a proxy, you need to define a custom
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000531transport. The following example shows how:
Georg Brandl116aa622007-08-15 14:28:22 +0000532
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000533.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535::
536
Georg Brandl24420152008-05-26 16:32:26 +0000537 import xmlrpc.client, http.client
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Georg Brandl38eceaa2008-05-26 11:14:17 +0000539 class ProxiedTransport(xmlrpc.client.Transport):
Georg Brandl116aa622007-08-15 14:28:22 +0000540 def set_proxy(self, proxy):
541 self.proxy = proxy
542 def make_connection(self, host):
543 self.realhost = host
Georg Brandl06788c92009-01-03 21:31:47 +0000544 h = http.client.HTTP(self.proxy)
545 return h
Georg Brandl116aa622007-08-15 14:28:22 +0000546 def send_request(self, connection, handler, request_body):
547 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
548 def send_host(self, connection, host):
549 connection.putheader('Host', self.realhost)
550
551 p = ProxiedTransport()
552 p.set_proxy('proxy-server:8080')
Georg Brandl38eceaa2008-05-26 11:14:17 +0000553 server = xmlrpc.client.Server('http://time.xmlrpc.com/RPC2', transport=p)
Collin Winterc79461b2007-09-01 23:34:30 +0000554 print(server.currentTime.getCurrentTime())
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000556
557Example of Client and Server Usage
558----------------------------------
559
560See :ref:`simplexmlrpcserver-example`.
561
562
Sandro Tosi9daf98d2011-08-20 17:05:56 +0200563.. rubric:: Footnotes
564
565.. [#] This approach has been first presented in `a discussion on xmlrpc.com
566 <http://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
567.. the link now points to webarchive since the one at
568.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
569.. doesn't reply)