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