blob: 3aa8be0708aa253a5639b3f3f9ff20420e010f6e [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`xmlrpclib` --- XML-RPC client access
2==========================================
3
4.. module:: xmlrpclib
5 :synopsis: XML-RPC client access.
6.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
7.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
8
Georg Brandle2caef72008-05-26 10:47:43 +00009.. note::
10 The :mod:`xmlrpclib` module has been renamed to :mod:`xmlrpc.client` in
Ezio Melotti510ff542012-05-03 19:21:40 +030011 Python 3. The :term:`2to3` tool will automatically adapt imports when
12 converting your sources to Python 3.
Georg Brandle2caef72008-05-26 10:47:43 +000013
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
Georg Brandlb19be572007-12-29 10:57:00 +000015.. XXX Not everything is documented yet. It might be good to describe
16 Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
18.. versionadded:: 2.2
19
Éric Araujo29a0b572011-08-19 02:14:03 +020020**Source code:** :source:`Lib/xmlrpclib.py`
21
22--------------
23
Georg Brandl8ec7f652007-08-15 14:28:01 +000024XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
25transport. With it, a client can call methods with parameters on a remote
26server (the server is named by a URI) and get back structured data. This module
27supports writing XML-RPC client code; it handles all the details of translating
28between conformable Python objects and XML on the wire.
29
30
Christian Heimes23790b42013-03-26 17:53:05 +010031.. warning::
32
33 The :mod:`xmlrpclib` module is not secure against maliciously
34 constructed data. If you need to parse untrusted or unauthenticated data see
35 :ref:`xml-vulnerabilities`.
36
Benjamin Petersone3e7d402014-11-23 21:02:02 -060037.. versionchanged:: 2.7.9
Benjamin Peterson078ece22014-10-13 11:53:54 -040038
Benjamin Petersone3e7d402014-11-23 21:02:02 -060039 For https URIs, :mod:`xmlrpclib` now performs all the necessary certificate
40 and hostname checks by default
Christian Heimes23790b42013-03-26 17:53:05 +010041
Georg Brandl8ec7f652007-08-15 14:28:01 +000042.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]])
43
44 A :class:`ServerProxy` instance is an object that manages communication with a
45 remote XML-RPC server. The required first argument is a URI (Uniform Resource
46 Indicator), and will normally be the URL of the server. The optional second
47 argument is a transport factory instance; by default it is an internal
48 :class:`SafeTransport` instance for https: URLs and an internal HTTP
49 :class:`Transport` instance otherwise. The optional third argument is an
50 encoding, by default UTF-8. The optional fourth argument is a debugging flag.
51 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
54 all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
55 description. The *use_datetime* flag can be used to cause date/time values to
56 be presented as :class:`datetime.datetime` objects; this is false by default.
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000057 :class:`datetime.datetime` objects may be passed to calls.
Georg Brandl8ec7f652007-08-15 14:28:01 +000058
59 Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
60 Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass``
61 portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
62 the remote server as part of the connection process when invoking an XML-RPC
63 method. You only need to use this if the remote server requires a Basic
64 Authentication user and password.
65
66 The returned instance is a proxy object with methods that can be used to invoke
67 corresponding RPC calls on the remote server. If the remote server supports the
68 introspection API, the proxy can also be used to query the remote server for the
69 methods it supports (service discovery) and fetch other server-associated
70 metadata.
71
72 :class:`ServerProxy` instance methods take Python basic types and objects as
73 arguments and return Python basic types and classes. Types that are conformable
74 (e.g. that can be marshalled through XML), include the following (and except
75 where noted, they are unmarshalled as the same Python type):
76
77 +---------------------------------+---------------------------------------------+
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 +---------------------------------+---------------------------------------------+
99 | :const:`dates` | in seconds since the epoch (pass in an |
100 | | instance of the :class:`DateTime` class) or |
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000101 | | a :class:`datetime.datetime` instance. |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000102 +---------------------------------+---------------------------------------------+
103 | :const:`binary data` | pass in an instance of the :class:`Binary` |
104 | | wrapper class |
105 +---------------------------------+---------------------------------------------+
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
111 :exc:`Error`. Note that even though starting with Python 2.2 you can subclass
Georg Brandld7d4fd72009-07-26 14:37:28 +0000112 built-in types, the xmlrpclib module currently does not marshal instances of such
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113 subclasses.
114
115 When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
116 will be automatically escaped. However, it's the caller's responsibility to
117 ensure that the string is free of characters that aren't allowed in XML, such as
118 the control characters with ASCII values between 0 and 31 (except, of course,
119 tab, newline and carriage return); failing to do this will result in an XML-RPC
120 request that isn't well-formed XML. If you have to pass arbitrary strings via
121 XML-RPC, use the :class:`Binary` wrapper class described below.
122
123 :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
124 compatibility. New code should use :class:`ServerProxy`.
125
126 .. versionchanged:: 2.5
127 The *use_datetime* flag was added.
128
129 .. versionchanged:: 2.6
Georg Brandla7395032007-10-21 12:15:05 +0000130 Instances of :term:`new-style class`\es can be passed in if they have an
131 *__dict__* attribute and don't have a base class that is marshalled in a
132 special way.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133
134
135.. seealso::
136
137 `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
Andrew M. Kuchlingde680372008-01-11 19:33:24 +0000138 A good description of XML-RPC operation and client software in several languages.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139 Contains pretty much everything an XML-RPC client developer needs to know.
140
Andrew M. Kuchlingde680372008-01-11 19:33:24 +0000141 `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
142 Describes the XML-RPC protocol extension for introspection.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
Skip Montanaro6d9aafa2008-04-22 22:45:09 +0000144 `XML-RPC Specification <http://www.xmlrpc.com/spec>`_
145 The official specification.
146
147 `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
148 Fredrik Lundh's "unofficial errata, intended to clarify certain
149 details in the XML-RPC specification, as well as hint at
150 'best practices' to use when designing your own XML-RPC
151 implementations."
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
153.. _serverproxy-objects:
154
155ServerProxy Objects
156-------------------
157
158A :class:`ServerProxy` instance has a method corresponding to each remote
159procedure call accepted by the XML-RPC server. Calling the method performs an
160RPC, dispatched by both name and argument signature (e.g. the same method name
161can be overloaded with multiple argument signatures). The RPC finishes by
162returning a value, which may be either returned data in a conformant type or a
163:class:`Fault` or :class:`ProtocolError` object indicating an error.
164
165Servers that support the XML introspection API support some common methods
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700166grouped under the reserved :attr:`system` attribute:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167
168
169.. method:: ServerProxy.system.listMethods()
170
171 This method returns a list of strings, one for each (non-system) method
172 supported by the XML-RPC server.
173
174
175.. method:: ServerProxy.system.methodSignature(name)
176
177 This method takes one parameter, the name of a method implemented by the XML-RPC
Georg Brandlf5f045e2009-05-04 20:45:13 +0000178 server. It returns an array of possible signatures for this method. A signature
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179 is an array of types. The first of these types is the return type of the method,
180 the rest are parameters.
181
182 Because multiple signatures (ie. overloading) is permitted, this method returns
183 a list of signatures rather than a singleton.
184
185 Signatures themselves are restricted to the top level parameters expected by a
186 method. For instance if a method expects one array of structs as a parameter,
187 and it returns a string, its signature is simply "string, array". If it expects
188 three integers and returns a string, its signature is "string, int, int, int".
189
190 If no signature is defined for the method, a non-array value is returned. In
191 Python this means that the type of the returned value will be something other
Georg Brandlf5f045e2009-05-04 20:45:13 +0000192 than list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194
195.. method:: ServerProxy.system.methodHelp(name)
196
197 This method takes one parameter, the name of a method implemented by the XML-RPC
198 server. It returns a documentation string describing the use of that method. If
199 no such string is available, an empty string is returned. The documentation
200 string may contain HTML markup.
201
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203.. _boolean-objects:
204
205Boolean Objects
206---------------
207
208This class may be initialized from any Python value; the instance returned
209depends only on its truth value. It supports various Python operators through
210:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
211methods, all implemented in the obvious ways.
212
213It also has the following method, supported mainly for internal use by the
214unmarshalling code:
215
216
217.. method:: Boolean.encode(out)
218
219 Write the XML-RPC encoding of this Boolean item to the out stream object.
220
Georg Brandl0a0cf162007-12-03 20:03:46 +0000221A working example follows. The server code::
222
223 import xmlrpclib
224 from SimpleXMLRPCServer import SimpleXMLRPCServer
225
226 def is_even(n):
227 return n%2 == 0
228
229 server = SimpleXMLRPCServer(("localhost", 8000))
230 print "Listening on port 8000..."
231 server.register_function(is_even, "is_even")
232 server.serve_forever()
233
234The client code for the preceding server::
235
236 import xmlrpclib
237
238 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
239 print "3 is even: %s" % str(proxy.is_even(3))
240 print "100 is even: %s" % str(proxy.is_even(100))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241
242.. _datetime-objects:
243
244DateTime Objects
245----------------
246
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000247This class may be initialized with seconds since the epoch, a time
248tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
249instance. It has the following methods, supported mainly for internal
250use by the marshalling/unmarshalling code:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251
252
253.. method:: DateTime.decode(string)
254
255 Accept a string as the instance's new time value.
256
257
258.. method:: DateTime.encode(out)
259
260 Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
261 object.
262
263It also supports certain of Python's built-in operators through :meth:`__cmp__`
264and :meth:`__repr__` methods.
265
Georg Brandl0a0cf162007-12-03 20:03:46 +0000266A working example follows. The server code::
267
268 import datetime
269 from SimpleXMLRPCServer import SimpleXMLRPCServer
270 import xmlrpclib
271
272 def today():
273 today = datetime.datetime.today()
274 return xmlrpclib.DateTime(today)
275
276 server = SimpleXMLRPCServer(("localhost", 8000))
277 print "Listening on port 8000..."
278 server.register_function(today, "today")
279 server.serve_forever()
280
281The client code for the preceding server::
282
283 import xmlrpclib
284 import datetime
285
286 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
287
288 today = proxy.today()
289 # convert the ISO8601 string to a datetime object
290 converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
291 print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000292
293.. _binary-objects:
294
295Binary Objects
296--------------
297
298This class may be initialized from string data (which may include NULs). The
299primary access to the content of a :class:`Binary` object is provided by an
300attribute:
301
302
303.. attribute:: Binary.data
304
305 The binary data encapsulated by the :class:`Binary` instance. The data is
306 provided as an 8-bit string.
307
308:class:`Binary` objects have the following methods, supported mainly for
309internal use by the marshalling/unmarshalling code:
310
311
312.. method:: Binary.decode(string)
313
314 Accept a base64 string and decode it as the instance's new data.
315
316
317.. method:: Binary.encode(out)
318
319 Write the XML-RPC base 64 encoding of this binary item to the out stream object.
320
Skip Montanaro6d9aafa2008-04-22 22:45:09 +0000321 The encoded data will have newlines every 76 characters as per
322 `RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
323 which was the de facto standard base64 specification when the
324 XML-RPC spec was written.
325
Georg Brandl8ec7f652007-08-15 14:28:01 +0000326It also supports certain of Python's built-in operators through a
327:meth:`__cmp__` method.
328
Georg Brandl0a0cf162007-12-03 20:03:46 +0000329Example usage of the binary objects. We're going to transfer an image over
330XMLRPC::
331
332 from SimpleXMLRPCServer import SimpleXMLRPCServer
333 import xmlrpclib
334
335 def python_logo():
Victor Stinner75d3fb12010-01-30 02:00:26 +0000336 with open("python_logo.jpg", "rb") as handle:
Georg Brandl34feea32009-02-07 12:21:17 +0000337 return xmlrpclib.Binary(handle.read())
Georg Brandl0a0cf162007-12-03 20:03:46 +0000338
339 server = SimpleXMLRPCServer(("localhost", 8000))
340 print "Listening on port 8000..."
341 server.register_function(python_logo, 'python_logo')
342
343 server.serve_forever()
344
345The client gets the image and saves it to a file::
346
347 import xmlrpclib
348
349 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
Victor Stinner75d3fb12010-01-30 02:00:26 +0000350 with open("fetched_python_logo.jpg", "wb") as handle:
Georg Brandl34feea32009-02-07 12:21:17 +0000351 handle.write(proxy.python_logo().data)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352
353.. _fault-objects:
354
355Fault Objects
356-------------
357
358A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700359objects have the following attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
361
362.. attribute:: Fault.faultCode
363
364 A string indicating the fault type.
365
366
367.. attribute:: Fault.faultString
368
369 A string containing a diagnostic message associated with the fault.
370
Georg Brandl0a0cf162007-12-03 20:03:46 +0000371In the following example we're going to intentionally cause a :exc:`Fault` by
372returning a complex type object. The server code::
373
374 from SimpleXMLRPCServer import SimpleXMLRPCServer
375
376 # A marshalling error is going to occur because we're returning a
377 # complex number
378 def add(x,y):
379 return x+y+0j
380
381 server = SimpleXMLRPCServer(("localhost", 8000))
382 print "Listening on port 8000..."
383 server.register_function(add, 'add')
384
385 server.serve_forever()
386
387The client code for the preceding server::
388
389 import xmlrpclib
390
391 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
392 try:
393 proxy.add(2, 5)
Andrew Svetlov1625d882012-10-30 21:56:43 +0200394 except xmlrpclib.Fault as err:
Benjamin Peterson90f36732008-07-12 20:16:19 +0000395 print "A fault occurred"
Georg Brandl0a0cf162007-12-03 20:03:46 +0000396 print "Fault code: %d" % err.faultCode
397 print "Fault string: %s" % err.faultString
398
399
Georg Brandl8ec7f652007-08-15 14:28:01 +0000400
401.. _protocol-error-objects:
402
403ProtocolError Objects
404---------------------
405
406A :class:`ProtocolError` object describes a protocol error in the underlying
407transport layer (such as a 404 'not found' error if the server named by the URI
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700408does not exist). It has the following attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409
410
411.. attribute:: ProtocolError.url
412
413 The URI or URL that triggered the error.
414
415
416.. attribute:: ProtocolError.errcode
417
418 The error code.
419
420
421.. attribute:: ProtocolError.errmsg
422
423 The error message or diagnostic string.
424
425
426.. attribute:: ProtocolError.headers
427
428 A string containing the headers of the HTTP/HTTPS request that triggered the
429 error.
430
Georg Brandl0a0cf162007-12-03 20:03:46 +0000431In the following example we're going to intentionally cause a :exc:`ProtocolError`
Georg Brandl53ffca52010-01-30 17:57:48 +0000432by providing an URI that doesn't point to an XMLRPC server::
Georg Brandl0a0cf162007-12-03 20:03:46 +0000433
434 import xmlrpclib
435
Georg Brandl53ffca52010-01-30 17:57:48 +0000436 # create a ServerProxy with an URI that doesn't respond to XMLRPC requests
437 proxy = xmlrpclib.ServerProxy("http://www.google.com/")
Georg Brandl0a0cf162007-12-03 20:03:46 +0000438
439 try:
440 proxy.some_method()
Andrew Svetlov1625d882012-10-30 21:56:43 +0200441 except xmlrpclib.ProtocolError as err:
Benjamin Peterson90f36732008-07-12 20:16:19 +0000442 print "A protocol error occurred"
Georg Brandl0a0cf162007-12-03 20:03:46 +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 Brandl8ec7f652007-08-15 14:28:01 +0000447
448MultiCall Objects
449-----------------
450
451.. versionadded:: 2.4
452
Sandro Tosi9b680922011-08-20 17:05:15 +0200453The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
454remote server into a single request [#]_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000455
456
457.. class:: MultiCall(server)
458
459 Create an object used to boxcar method calls. *server* is the eventual target of
460 the call. Calls can be made to the result object, but they will immediately
461 return ``None``, and only store the call name and parameters in the
462 :class:`MultiCall` object. Calling the object itself causes all stored calls to
463 be transmitted as a single ``system.multicall`` request. The result of this call
Georg Brandlcf3fb252007-10-21 10:52:38 +0000464 is a :term:`generator`; iterating over this generator yields the individual
465 results.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000466
Georg Brandl0a0cf162007-12-03 20:03:46 +0000467A usage example of this class follows. The server code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000468
Georg Brandl0a0cf162007-12-03 20:03:46 +0000469 from SimpleXMLRPCServer import SimpleXMLRPCServer
470
471 def add(x,y):
472 return x+y
473
474 def subtract(x, y):
475 return x-y
476
477 def multiply(x, y):
478 return x*y
479
480 def divide(x, y):
481 return x/y
482
483 # A simple server with simple arithmetic functions
484 server = SimpleXMLRPCServer(("localhost", 8000))
485 print "Listening on port 8000..."
486 server.register_multicall_functions()
487 server.register_function(add, 'add')
488 server.register_function(subtract, 'subtract')
489 server.register_function(multiply, 'multiply')
490 server.register_function(divide, 'divide')
491 server.serve_forever()
492
493The client code for the preceding server::
494
495 import xmlrpclib
496
497 proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
498 multicall = xmlrpclib.MultiCall(proxy)
499 multicall.add(7,3)
500 multicall.subtract(7,3)
501 multicall.multiply(7,3)
502 multicall.divide(7,3)
503 result = multicall()
504
505 print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
507
508Convenience Functions
509---------------------
510
511
512.. function:: boolean(value)
513
514 Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
515 ``False``.
516
517
518.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])
519
520 Convert *params* into an XML-RPC request. or into a response if *methodresponse*
521 is true. *params* can be either a tuple of arguments or an instance of the
522 :exc:`Fault` exception class. If *methodresponse* is true, only a single value
523 can be returned, meaning that *params* must be of length 1. *encoding*, if
524 supplied, is the encoding to use in the generated XML; the default is UTF-8.
525 Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
526 it via an extension, provide a true value for *allow_none*.
527
528
529.. function:: loads(data[, use_datetime])
530
531 Convert an XML-RPC request or response into Python objects, a ``(params,
532 methodname)``. *params* is a tuple of argument; *methodname* is a string, or
533 ``None`` if no method name is present in the packet. If the XML-RPC packet
534 represents a fault condition, this function will raise a :exc:`Fault` exception.
535 The *use_datetime* flag can be used to cause date/time values to be presented as
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +0000536 :class:`datetime.datetime` objects; this is false by default.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
538 .. versionchanged:: 2.5
539 The *use_datetime* flag was added.
540
541
542.. _xmlrpc-client-example:
543
544Example of Client Usage
545-----------------------
546
547::
548
549 # simple test program (from the XML-RPC specification)
550 from xmlrpclib import ServerProxy, Error
551
552 # server = ServerProxy("http://localhost:8000") # local server
553 server = ServerProxy("http://betty.userland.com")
554
555 print server
556
557 try:
558 print server.examples.getStateName(41)
Andrew Svetlov1625d882012-10-30 21:56:43 +0200559 except Error as v:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000560 print "ERROR", v
561
562To access an XML-RPC server through a proxy, you need to define a custom
Georg Brandlb19be572007-12-29 10:57:00 +0000563transport. The following example shows how:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564
Georg Brandlb19be572007-12-29 10:57:00 +0000565.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
Georg Brandl8ec7f652007-08-15 14:28:01 +0000566
567::
568
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000569 import xmlrpclib, httplib
Georg Brandl8ec7f652007-08-15 14:28:01 +0000570
571 class ProxiedTransport(xmlrpclib.Transport):
572 def set_proxy(self, proxy):
573 self.proxy = proxy
574 def make_connection(self, host):
575 self.realhost = host
Georg Brandl7044b112009-01-03 21:04:55 +0000576 h = httplib.HTTP(self.proxy)
577 return h
Georg Brandl8ec7f652007-08-15 14:28:01 +0000578 def send_request(self, connection, handler, request_body):
579 connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
580 def send_host(self, connection, host):
581 connection.putheader('Host', self.realhost)
582
583 p = ProxiedTransport()
584 p.set_proxy('proxy-server:8080')
585 server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
586 print server.currentTime.getCurrentTime()
587
Georg Brandl0a0cf162007-12-03 20:03:46 +0000588
589Example of Client and Server Usage
590----------------------------------
591
592See :ref:`simplexmlrpcserver-example`.
593
594
Sandro Tosi9b680922011-08-20 17:05:15 +0200595.. rubric:: Footnotes
596
597.. [#] This approach has been first presented in `a discussion on xmlrpc.com
598 <http://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
599.. the link now points to webarchive since the one at
600.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
601.. doesn't reply)