Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`xmlrpclib` --- XML-RPC client access |
| 3 | ========================================== |
| 4 | |
| 5 | .. module:: xmlrpclib |
| 6 | :synopsis: XML-RPC client access. |
| 7 | .. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com> |
| 8 | .. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com> |
| 9 | |
| 10 | |
| 11 | .. % Not everything is documented yet. It might be good to describe |
| 12 | .. % Marshaller, Unmarshaller, getparser, dumps, loads, and Transport. |
| 13 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a |
| 15 | transport. With it, a client can call methods with parameters on a remote |
| 16 | server (the server is named by a URI) and get back structured data. This module |
| 17 | supports writing XML-RPC client code; it handles all the details of translating |
| 18 | between conformable Python objects and XML on the wire. |
| 19 | |
| 20 | |
| 21 | .. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]]) |
| 22 | |
| 23 | A :class:`ServerProxy` instance is an object that manages communication with a |
| 24 | remote XML-RPC server. The required first argument is a URI (Uniform Resource |
| 25 | Indicator), and will normally be the URL of the server. The optional second |
| 26 | argument is a transport factory instance; by default it is an internal |
| 27 | :class:`SafeTransport` instance for https: URLs and an internal HTTP |
| 28 | :class:`Transport` instance otherwise. The optional third argument is an |
| 29 | encoding, by default UTF-8. The optional fourth argument is a debugging flag. |
| 30 | If *allow_none* is true, the Python constant ``None`` will be translated into |
| 31 | XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is |
| 32 | a commonly-used extension to the XML-RPC specification, but isn't supported by |
| 33 | all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a |
| 34 | description. The *use_datetime* flag can be used to cause date/time values to |
| 35 | be presented as :class:`datetime.datetime` objects; this is false by default. |
| 36 | :class:`datetime.datetime`, :class:`datetime.date` and :class:`datetime.time` |
| 37 | objects may be passed to calls. :class:`datetime.date` objects are converted |
| 38 | with a time of "00:00:00". :class:`datetime.time` objects are converted using |
| 39 | today's date. |
| 40 | |
| 41 | Both the HTTP and HTTPS transports support the URL syntax extension for HTTP |
| 42 | Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass`` |
| 43 | portion will be base64-encoded as an HTTP 'Authorization' header, and sent to |
| 44 | the remote server as part of the connection process when invoking an XML-RPC |
| 45 | method. You only need to use this if the remote server requires a Basic |
| 46 | Authentication user and password. |
| 47 | |
| 48 | The returned instance is a proxy object with methods that can be used to invoke |
| 49 | corresponding RPC calls on the remote server. If the remote server supports the |
| 50 | introspection API, the proxy can also be used to query the remote server for the |
| 51 | methods it supports (service discovery) and fetch other server-associated |
| 52 | metadata. |
| 53 | |
| 54 | :class:`ServerProxy` instance methods take Python basic types and objects as |
| 55 | arguments and return Python basic types and classes. Types that are conformable |
| 56 | (e.g. that can be marshalled through XML), include the following (and except |
| 57 | where noted, they are unmarshalled as the same Python type): |
| 58 | |
| 59 | +---------------------------------+---------------------------------------------+ |
| 60 | | Name | Meaning | |
| 61 | +=================================+=============================================+ |
| 62 | | :const:`boolean` | The :const:`True` and :const:`False` | |
| 63 | | | constants | |
| 64 | +---------------------------------+---------------------------------------------+ |
| 65 | | :const:`integers` | Pass in directly | |
| 66 | +---------------------------------+---------------------------------------------+ |
| 67 | | :const:`floating-point numbers` | Pass in directly | |
| 68 | +---------------------------------+---------------------------------------------+ |
| 69 | | :const:`strings` | Pass in directly | |
| 70 | +---------------------------------+---------------------------------------------+ |
| 71 | | :const:`arrays` | Any Python sequence type containing | |
| 72 | | | conformable elements. Arrays are returned | |
| 73 | | | as lists | |
| 74 | +---------------------------------+---------------------------------------------+ |
| 75 | | :const:`structures` | A Python dictionary. Keys must be strings, | |
| 76 | | | values may be any conformable type. Objects | |
| 77 | | | of user-defined classes can be passed in; | |
| 78 | | | only their *__dict__* attribute is | |
| 79 | | | transmitted. | |
| 80 | +---------------------------------+---------------------------------------------+ |
| 81 | | :const:`dates` | in seconds since the epoch (pass in an | |
| 82 | | | instance of the :class:`DateTime` class) or | |
| 83 | | | a :class:`datetime.datetime`, | |
| 84 | | | :class:`datetime.date` or | |
| 85 | | | :class:`datetime.time` instance | |
| 86 | +---------------------------------+---------------------------------------------+ |
| 87 | | :const:`binary data` | pass in an instance of the :class:`Binary` | |
| 88 | | | wrapper class | |
| 89 | +---------------------------------+---------------------------------------------+ |
| 90 | |
| 91 | This is the full set of data types supported by XML-RPC. Method calls may also |
| 92 | raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or |
| 93 | :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer. |
| 94 | Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called |
| 95 | :exc:`Error`. Note that even though starting with Python 2.2 you can subclass |
| 96 | builtin types, the xmlrpclib module currently does not marshal instances of such |
| 97 | subclasses. |
| 98 | |
| 99 | When passing strings, characters special to XML such as ``<``, ``>``, and ``&`` |
| 100 | will be automatically escaped. However, it's the caller's responsibility to |
| 101 | ensure that the string is free of characters that aren't allowed in XML, such as |
| 102 | the control characters with ASCII values between 0 and 31 (except, of course, |
| 103 | tab, newline and carriage return); failing to do this will result in an XML-RPC |
| 104 | request that isn't well-formed XML. If you have to pass arbitrary strings via |
| 105 | XML-RPC, use the :class:`Binary` wrapper class described below. |
| 106 | |
| 107 | :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards |
| 108 | compatibility. New code should use :class:`ServerProxy`. |
| 109 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | |
| 111 | .. seealso:: |
| 112 | |
| 113 | `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_ |
| 114 | A good description of XML operation and client software in several languages. |
| 115 | Contains pretty much everything an XML-RPC client developer needs to know. |
| 116 | |
| 117 | `XML-RPC Hacks page <http://xmlrpc-c.sourceforge.net/hacks.php>`_ |
| 118 | Extensions for various open-source libraries to support introspection and |
| 119 | multicall. |
| 120 | |
| 121 | |
| 122 | .. _serverproxy-objects: |
| 123 | |
| 124 | ServerProxy Objects |
| 125 | ------------------- |
| 126 | |
| 127 | A :class:`ServerProxy` instance has a method corresponding to each remote |
| 128 | procedure call accepted by the XML-RPC server. Calling the method performs an |
| 129 | RPC, dispatched by both name and argument signature (e.g. the same method name |
| 130 | can be overloaded with multiple argument signatures). The RPC finishes by |
| 131 | returning a value, which may be either returned data in a conformant type or a |
| 132 | :class:`Fault` or :class:`ProtocolError` object indicating an error. |
| 133 | |
| 134 | Servers that support the XML introspection API support some common methods |
| 135 | grouped under the reserved :attr:`system` member: |
| 136 | |
| 137 | |
| 138 | .. method:: ServerProxy.system.listMethods() |
| 139 | |
| 140 | This method returns a list of strings, one for each (non-system) method |
| 141 | supported by the XML-RPC server. |
| 142 | |
| 143 | |
| 144 | .. method:: ServerProxy.system.methodSignature(name) |
| 145 | |
| 146 | This method takes one parameter, the name of a method implemented by the XML-RPC |
| 147 | server.It returns an array of possible signatures for this method. A signature |
| 148 | is an array of types. The first of these types is the return type of the method, |
| 149 | the rest are parameters. |
| 150 | |
| 151 | Because multiple signatures (ie. overloading) is permitted, this method returns |
| 152 | a list of signatures rather than a singleton. |
| 153 | |
| 154 | Signatures themselves are restricted to the top level parameters expected by a |
| 155 | method. For instance if a method expects one array of structs as a parameter, |
| 156 | and it returns a string, its signature is simply "string, array". If it expects |
| 157 | three integers and returns a string, its signature is "string, int, int, int". |
| 158 | |
| 159 | If no signature is defined for the method, a non-array value is returned. In |
| 160 | Python this means that the type of the returned value will be something other |
| 161 | that list. |
| 162 | |
| 163 | |
| 164 | .. method:: ServerProxy.system.methodHelp(name) |
| 165 | |
| 166 | This method takes one parameter, the name of a method implemented by the XML-RPC |
| 167 | server. It returns a documentation string describing the use of that method. If |
| 168 | no such string is available, an empty string is returned. The documentation |
| 169 | string may contain HTML markup. |
| 170 | |
| 171 | Introspection methods are currently supported by servers written in PHP, C and |
| 172 | Microsoft .NET. Partial introspection support is included in recent updates to |
| 173 | UserLand Frontier. Introspection support for Perl, Python and Java is available |
| 174 | at the `XML-RPC Hacks <http://xmlrpc-c.sourceforge.net/hacks.php>`_ page. |
| 175 | |
| 176 | |
| 177 | .. _boolean-objects: |
| 178 | |
| 179 | Boolean Objects |
| 180 | --------------- |
| 181 | |
| 182 | This class may be initialized from any Python value; the instance returned |
| 183 | depends only on its truth value. It supports various Python operators through |
| 184 | :meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__bool__` |
| 185 | methods, all implemented in the obvious ways. |
| 186 | |
| 187 | It also has the following method, supported mainly for internal use by the |
| 188 | unmarshalling code: |
| 189 | |
| 190 | |
| 191 | .. method:: Boolean.encode(out) |
| 192 | |
| 193 | Write the XML-RPC encoding of this Boolean item to the out stream object. |
| 194 | |
| 195 | |
| 196 | .. _datetime-objects: |
| 197 | |
| 198 | DateTime Objects |
| 199 | ---------------- |
| 200 | |
| 201 | This class may be initialized with seconds since the epoch, a time tuple, an ISO |
| 202 | 8601 time/date string, or a :class:`datetime.datetime`, :class:`datetime.date` |
| 203 | or :class:`datetime.time` instance. It has the following methods, supported |
| 204 | mainly for internal use by the marshalling/unmarshalling code: |
| 205 | |
| 206 | |
| 207 | .. method:: DateTime.decode(string) |
| 208 | |
| 209 | Accept a string as the instance's new time value. |
| 210 | |
| 211 | |
| 212 | .. method:: DateTime.encode(out) |
| 213 | |
| 214 | Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream |
| 215 | object. |
| 216 | |
| 217 | It also supports certain of Python's built-in operators through :meth:`__cmp__` |
| 218 | and :meth:`__repr__` methods. |
| 219 | |
| 220 | |
| 221 | .. _binary-objects: |
| 222 | |
| 223 | Binary Objects |
| 224 | -------------- |
| 225 | |
| 226 | This class may be initialized from string data (which may include NULs). The |
| 227 | primary access to the content of a :class:`Binary` object is provided by an |
| 228 | attribute: |
| 229 | |
| 230 | |
| 231 | .. attribute:: Binary.data |
| 232 | |
| 233 | The binary data encapsulated by the :class:`Binary` instance. The data is |
| 234 | provided as an 8-bit string. |
| 235 | |
| 236 | :class:`Binary` objects have the following methods, supported mainly for |
| 237 | internal use by the marshalling/unmarshalling code: |
| 238 | |
| 239 | |
| 240 | .. method:: Binary.decode(string) |
| 241 | |
| 242 | Accept a base64 string and decode it as the instance's new data. |
| 243 | |
| 244 | |
| 245 | .. method:: Binary.encode(out) |
| 246 | |
| 247 | Write the XML-RPC base 64 encoding of this binary item to the out stream object. |
| 248 | |
| 249 | It also supports certain of Python's built-in operators through a |
| 250 | :meth:`__cmp__` method. |
| 251 | |
| 252 | |
| 253 | .. _fault-objects: |
| 254 | |
| 255 | Fault Objects |
| 256 | ------------- |
| 257 | |
| 258 | A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault |
| 259 | objects have the following members: |
| 260 | |
| 261 | |
| 262 | .. attribute:: Fault.faultCode |
| 263 | |
| 264 | A string indicating the fault type. |
| 265 | |
| 266 | |
| 267 | .. attribute:: Fault.faultString |
| 268 | |
| 269 | A string containing a diagnostic message associated with the fault. |
| 270 | |
| 271 | |
| 272 | .. _protocol-error-objects: |
| 273 | |
| 274 | ProtocolError Objects |
| 275 | --------------------- |
| 276 | |
| 277 | A :class:`ProtocolError` object describes a protocol error in the underlying |
| 278 | transport layer (such as a 404 'not found' error if the server named by the URI |
| 279 | does not exist). It has the following members: |
| 280 | |
| 281 | |
| 282 | .. attribute:: ProtocolError.url |
| 283 | |
| 284 | The URI or URL that triggered the error. |
| 285 | |
| 286 | |
| 287 | .. attribute:: ProtocolError.errcode |
| 288 | |
| 289 | The error code. |
| 290 | |
| 291 | |
| 292 | .. attribute:: ProtocolError.errmsg |
| 293 | |
| 294 | The error message or diagnostic string. |
| 295 | |
| 296 | |
| 297 | .. attribute:: ProtocolError.headers |
| 298 | |
Guido van Rossum | 460add4 | 2007-08-23 02:13:35 +0000 | [diff] [blame] | 299 | A dict containing the headers of the HTTP/HTTPS request that triggered the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 300 | error. |
| 301 | |
| 302 | |
| 303 | MultiCall Objects |
| 304 | ----------------- |
| 305 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 306 | In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to |
| 307 | encapsulate multiple calls to a remote server into a single request. |
| 308 | |
| 309 | |
| 310 | .. class:: MultiCall(server) |
| 311 | |
| 312 | Create an object used to boxcar method calls. *server* is the eventual target of |
| 313 | the call. Calls can be made to the result object, but they will immediately |
| 314 | return ``None``, and only store the call name and parameters in the |
| 315 | :class:`MultiCall` object. Calling the object itself causes all stored calls to |
| 316 | be transmitted as a single ``system.multicall`` request. The result of this call |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame^] | 317 | is a :term:`generator`; iterating over this generator yields the individual |
| 318 | results. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 319 | |
| 320 | A usage example of this class is :: |
| 321 | |
| 322 | multicall = MultiCall(server_proxy) |
| 323 | multicall.add(2,3) |
| 324 | multicall.get_address("Guido") |
| 325 | add_result, address = multicall() |
| 326 | |
| 327 | |
| 328 | Convenience Functions |
| 329 | --------------------- |
| 330 | |
| 331 | |
| 332 | .. function:: boolean(value) |
| 333 | |
| 334 | Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or |
| 335 | ``False``. |
| 336 | |
| 337 | |
| 338 | .. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]]) |
| 339 | |
| 340 | Convert *params* into an XML-RPC request. or into a response if *methodresponse* |
| 341 | is true. *params* can be either a tuple of arguments or an instance of the |
| 342 | :exc:`Fault` exception class. If *methodresponse* is true, only a single value |
| 343 | can be returned, meaning that *params* must be of length 1. *encoding*, if |
| 344 | supplied, is the encoding to use in the generated XML; the default is UTF-8. |
| 345 | Python's :const:`None` value cannot be used in standard XML-RPC; to allow using |
| 346 | it via an extension, provide a true value for *allow_none*. |
| 347 | |
| 348 | |
| 349 | .. function:: loads(data[, use_datetime]) |
| 350 | |
| 351 | Convert an XML-RPC request or response into Python objects, a ``(params, |
| 352 | methodname)``. *params* is a tuple of argument; *methodname* is a string, or |
| 353 | ``None`` if no method name is present in the packet. If the XML-RPC packet |
| 354 | represents a fault condition, this function will raise a :exc:`Fault` exception. |
| 355 | The *use_datetime* flag can be used to cause date/time values to be presented as |
| 356 | :class:`datetime.datetime` objects; this is false by default. Note that even if |
| 357 | you call an XML-RPC method with :class:`datetime.date` or :class:`datetime.time` |
| 358 | objects, they are converted to :class:`DateTime` objects internally, so only |
| 359 | :class:`datetime.datetime` objects will be returned. |
| 360 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 361 | |
| 362 | .. _xmlrpc-client-example: |
| 363 | |
| 364 | Example of Client Usage |
| 365 | ----------------------- |
| 366 | |
| 367 | :: |
| 368 | |
| 369 | # simple test program (from the XML-RPC specification) |
| 370 | from xmlrpclib import ServerProxy, Error |
| 371 | |
| 372 | # server = ServerProxy("http://localhost:8000") # local server |
| 373 | server = ServerProxy("http://betty.userland.com") |
| 374 | |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 375 | print(server) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 376 | |
| 377 | try: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 378 | print(server.examples.getStateName(41)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 379 | except Error as v: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 380 | print("ERROR", v) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | |
| 382 | To access an XML-RPC server through a proxy, you need to define a custom |
| 383 | transport. The following example, written by NoboNobo, shows how: |
| 384 | |
| 385 | .. % fill in original author's name if we ever learn it |
| 386 | |
| 387 | .. % Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html |
| 388 | |
| 389 | :: |
| 390 | |
| 391 | import xmlrpclib, httplib |
| 392 | |
| 393 | class ProxiedTransport(xmlrpclib.Transport): |
| 394 | def set_proxy(self, proxy): |
| 395 | self.proxy = proxy |
| 396 | def make_connection(self, host): |
| 397 | self.realhost = host |
| 398 | h = httplib.HTTP(self.proxy) |
| 399 | return h |
| 400 | def send_request(self, connection, handler, request_body): |
| 401 | connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) |
| 402 | def send_host(self, connection, host): |
| 403 | connection.putheader('Host', self.realhost) |
| 404 | |
| 405 | p = ProxiedTransport() |
| 406 | p.set_proxy('proxy-server:8080') |
| 407 | server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p) |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 408 | print(server.currentTime.getCurrentTime()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 409 | |