Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1 | # |
| 2 | # XML-RPC CLIENT LIBRARY |
| 3 | # $Id$ |
| 4 | # |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 5 | # an XML-RPC client interface for Python. |
| 6 | # |
| 7 | # the marshalling and response parser code can also be used to |
| 8 | # implement XML-RPC servers. |
| 9 | # |
| 10 | # Notes: |
| 11 | # this version is designed to work with Python 1.5.2 or newer. |
| 12 | # unicode encoding support requires at least Python 1.6. |
| 13 | # experimental HTTPS requires Python 2.0 built with SSL sockets. |
| 14 | # expat parser support requires Python 2.0 with pyexpat support. |
| 15 | # |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 16 | # History: |
| 17 | # 1999-01-14 fl Created |
| 18 | # 1999-01-15 fl Changed dateTime to use localtime |
| 19 | # 1999-01-16 fl Added Binary/base64 element, default to RPC2 service |
| 20 | # 1999-01-19 fl Fixed array data element (from Skip Montanaro) |
| 21 | # 1999-01-21 fl Fixed dateTime constructor, etc. |
| 22 | # 1999-02-02 fl Added fault handling, handle empty sequences, etc. |
| 23 | # 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro) |
| 24 | # 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8) |
| 25 | # 2000-11-28 fl Changed boolean to check the truth value of its argument |
| 26 | # 2001-02-24 fl Added encoding/Unicode/SafeTransport patches |
| 27 | # 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1) |
| 28 | # 2001-03-28 fl Make sure response tuple is a singleton |
| 29 | # 2001-03-29 fl Don't require empty params element (from Nicholas Riley) |
Fredrik Lundh | 78eedce | 2001-08-23 20:04:33 +0000 | [diff] [blame] | 30 | # 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2) |
| 31 | # 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod) |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 32 | # 2001-09-03 fl Allow Transport subclass to override getparser |
| 33 | # 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup) |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 34 | # 2001-10-01 fl Remove containers from memo cache when done with them |
| 35 | # 2001-10-01 fl Use faster escape method (80% dumps speedup) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 36 | # 2001-10-02 fl More dumps microtuning |
| 37 | # 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum) |
Skip Montanaro | 5e9c71b | 2001-10-10 15:56:34 +0000 | [diff] [blame] | 38 | # 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 39 | # 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems) |
Fredrik Lundh | b6ab93f | 2001-12-19 21:40:04 +0000 | [diff] [blame] | 40 | # 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 41 | # 2002-03-17 fl Avoid buffered read when possible (from James Rucker) |
| 42 | # 2002-04-07 fl Added pythondoc comments |
| 43 | # 2002-04-16 fl Added __str__ methods to datetime/binary wrappers |
| 44 | # 2002-05-15 fl Added error constants (from Andrew Kuchling) |
| 45 | # 2002-06-27 fl Merged with Python CVS version |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 46 | # 2002-10-22 fl Added basic authentication (based on code from Phillip Eby) |
Martin v. Löwis | 541342f | 2003-07-12 07:53:04 +0000 | [diff] [blame] | 47 | # 2003-01-22 sm Add support for the bool type |
| 48 | # 2003-02-27 gvr Remove apply calls |
| 49 | # 2003-04-24 sm Use cStringIO if available |
| 50 | # 2003-04-25 ak Add support for nil |
| 51 | # 2003-06-15 gn Add support for time.struct_time |
| 52 | # 2003-07-12 gp Correct marshalling of Faults |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 53 | # 2003-10-31 mvl Add multicall support |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 54 | # |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 55 | # Copyright (c) 1999-2002 by Secret Labs AB. |
| 56 | # Copyright (c) 1999-2002 by Fredrik Lundh. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 57 | # |
| 58 | # info@pythonware.com |
| 59 | # http://www.pythonware.com |
| 60 | # |
| 61 | # -------------------------------------------------------------------- |
| 62 | # The XML-RPC client interface is |
| 63 | # |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 64 | # Copyright (c) 1999-2002 by Secret Labs AB |
| 65 | # Copyright (c) 1999-2002 by Fredrik Lundh |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 66 | # |
| 67 | # By obtaining, using, and/or copying this software and/or its |
| 68 | # associated documentation, you agree that you have read, understood, |
| 69 | # and will comply with the following terms and conditions: |
| 70 | # |
| 71 | # Permission to use, copy, modify, and distribute this software and |
| 72 | # its associated documentation for any purpose and without fee is |
| 73 | # hereby granted, provided that the above copyright notice appears in |
| 74 | # all copies, and that both that copyright notice and this permission |
| 75 | # notice appear in supporting documentation, and that the name of |
| 76 | # Secret Labs AB or the author not be used in advertising or publicity |
| 77 | # pertaining to distribution of the software without specific, written |
| 78 | # prior permission. |
| 79 | # |
| 80 | # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD |
| 81 | # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- |
| 82 | # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR |
| 83 | # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY |
| 84 | # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, |
| 85 | # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS |
| 86 | # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE |
| 87 | # OF THIS SOFTWARE. |
| 88 | # -------------------------------------------------------------------- |
| 89 | |
| 90 | # |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 91 | # things to look into some day: |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 92 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 93 | # TODO: sort out True/False/boolean issues for Python 2.3 |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 94 | |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 95 | """ |
| 96 | An XML-RPC client interface for Python. |
| 97 | |
| 98 | The marshalling and response parser code can also be used to |
| 99 | implement XML-RPC servers. |
| 100 | |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 101 | Exported exceptions: |
| 102 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 103 | Error Base class for client errors |
| 104 | ProtocolError Indicates an HTTP protocol error |
| 105 | ResponseError Indicates a broken response package |
| 106 | Fault Indicates an XML-RPC fault package |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 107 | |
| 108 | Exported classes: |
| 109 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 110 | ServerProxy Represents a logical connection to an XML-RPC server |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 111 | |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 112 | MultiCall Executor of boxcared xmlrpc requests |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 113 | Boolean boolean wrapper to generate a "boolean" XML-RPC value |
| 114 | DateTime dateTime wrapper for an ISO 8601 string or time tuple or |
| 115 | localtime integer value to generate a "dateTime.iso8601" |
| 116 | XML-RPC value |
| 117 | Binary binary data wrapper |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 118 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 119 | SlowParser Slow but safe standard parser (based on xmllib) |
| 120 | Marshaller Generate an XML-RPC params chunk from a Python data structure |
| 121 | Unmarshaller Unmarshal an XML-RPC response from incoming XML event message |
| 122 | Transport Handles an HTTP transaction to an XML-RPC server |
| 123 | SafeTransport Handles an HTTPS transaction to an XML-RPC server |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 124 | |
| 125 | Exported constants: |
| 126 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 127 | True |
| 128 | False |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 129 | |
| 130 | Exported functions: |
| 131 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 132 | boolean Convert any Python value to an XML-RPC boolean |
| 133 | getparser Create instance of the fastest available parser & attach |
| 134 | to an unmarshalling object |
| 135 | dumps Convert an argument tuple or a Fault instance to an XML-RPC |
| 136 | request (or response, if the methodresponse option is used). |
| 137 | loads Convert an XML-RPC packet to unmarshalled data plus a method |
| 138 | name (None if not present). |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 139 | """ |
| 140 | |
Fred Drake | 2a2d970 | 2001-10-17 01:51:04 +0000 | [diff] [blame] | 141 | import re, string, time, operator |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 142 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 143 | from types import * |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 144 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 145 | # -------------------------------------------------------------------- |
| 146 | # Internal stuff |
| 147 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 148 | try: |
| 149 | unicode |
| 150 | except NameError: |
| 151 | unicode = None # unicode support not available |
| 152 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 153 | try: |
| 154 | _bool_is_builtin = False.__class__.__name__ == "bool" |
| 155 | except NameError: |
| 156 | _bool_is_builtin = 0 |
| 157 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 158 | def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search): |
| 159 | # decode non-ascii string (if possible) |
| 160 | if unicode and encoding and is8bit(data): |
| 161 | data = unicode(data, encoding) |
| 162 | return data |
| 163 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 164 | def escape(s, replace=string.replace): |
| 165 | s = replace(s, "&", "&") |
| 166 | s = replace(s, "<", "<") |
| 167 | return replace(s, ">", ">",) |
| 168 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 169 | if unicode: |
| 170 | def _stringify(string): |
| 171 | # convert to 7-bit ascii if possible |
| 172 | try: |
| 173 | return str(string) |
| 174 | except UnicodeError: |
| 175 | return string |
| 176 | else: |
| 177 | def _stringify(string): |
| 178 | return string |
| 179 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 180 | __version__ = "1.0.1" |
| 181 | |
| 182 | # xmlrpc integer limits |
| 183 | MAXINT = 2L**31-1 |
| 184 | MININT = -2L**31 |
| 185 | |
| 186 | # -------------------------------------------------------------------- |
| 187 | # Error constants (from Dan Libby's specification at |
| 188 | # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php) |
| 189 | |
| 190 | # Ranges of errors |
| 191 | PARSE_ERROR = -32700 |
| 192 | SERVER_ERROR = -32600 |
| 193 | APPLICATION_ERROR = -32500 |
| 194 | SYSTEM_ERROR = -32400 |
| 195 | TRANSPORT_ERROR = -32300 |
| 196 | |
| 197 | # Specific errors |
| 198 | NOT_WELLFORMED_ERROR = -32700 |
| 199 | UNSUPPORTED_ENCODING = -32701 |
| 200 | INVALID_ENCODING_CHAR = -32702 |
| 201 | INVALID_XMLRPC = -32600 |
| 202 | METHOD_NOT_FOUND = -32601 |
| 203 | INVALID_METHOD_PARAMS = -32602 |
| 204 | INTERNAL_ERROR = -32603 |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 205 | |
| 206 | # -------------------------------------------------------------------- |
| 207 | # Exceptions |
| 208 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 209 | ## |
| 210 | # Base class for all kinds of client-side errors. |
| 211 | |
Fredrik Lundh | 78eedce | 2001-08-23 20:04:33 +0000 | [diff] [blame] | 212 | class Error(Exception): |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 213 | """Base class for client errors.""" |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 214 | def __str__(self): |
| 215 | return repr(self) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 216 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 217 | ## |
| 218 | # Indicates an HTTP-level protocol error. This is raised by the HTTP |
| 219 | # transport layer, if the server returns an error code other than 200 |
| 220 | # (OK). |
| 221 | # |
| 222 | # @param url The target URL. |
| 223 | # @param errcode The HTTP error code. |
| 224 | # @param errmsg The HTTP error message. |
| 225 | # @param headers The HTTP header dictionary. |
| 226 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 227 | class ProtocolError(Error): |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 228 | """Indicates an HTTP protocol error.""" |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 229 | def __init__(self, url, errcode, errmsg, headers): |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 230 | Error.__init__(self) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 231 | self.url = url |
| 232 | self.errcode = errcode |
| 233 | self.errmsg = errmsg |
| 234 | self.headers = headers |
| 235 | def __repr__(self): |
| 236 | return ( |
| 237 | "<ProtocolError for %s: %s %s>" % |
| 238 | (self.url, self.errcode, self.errmsg) |
| 239 | ) |
| 240 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 241 | ## |
| 242 | # Indicates a broken XML-RPC response package. This exception is |
| 243 | # raised by the unmarshalling layer, if the XML-RPC response is |
| 244 | # malformed. |
| 245 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 246 | class ResponseError(Error): |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 247 | """Indicates a broken response package.""" |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 248 | pass |
| 249 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 250 | ## |
| 251 | # Indicates an XML-RPC fault response package. This exception is |
| 252 | # raised by the unmarshalling layer, if the XML-RPC response contains |
| 253 | # a fault string. This exception can also used as a class, to |
| 254 | # generate a fault XML-RPC message. |
| 255 | # |
| 256 | # @param faultCode The XML-RPC fault code. |
| 257 | # @param faultString The XML-RPC fault string. |
| 258 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 259 | class Fault(Error): |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 260 | """Indicates an XML-RPC fault package.""" |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 261 | def __init__(self, faultCode, faultString, **extra): |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 262 | Error.__init__(self) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 263 | self.faultCode = faultCode |
| 264 | self.faultString = faultString |
| 265 | def __repr__(self): |
| 266 | return ( |
| 267 | "<Fault %s: %s>" % |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 268 | (self.faultCode, repr(self.faultString)) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 269 | ) |
| 270 | |
| 271 | # -------------------------------------------------------------------- |
| 272 | # Special values |
| 273 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 274 | ## |
| 275 | # Wrapper for XML-RPC boolean values. Use the xmlrpclib.True and |
| 276 | # xmlrpclib.False constants, or the xmlrpclib.boolean() function, to |
| 277 | # generate boolean XML-RPC values. |
| 278 | # |
| 279 | # @param value A boolean value. Any true value is interpreted as True, |
| 280 | # all other values are interpreted as False. |
| 281 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 282 | if _bool_is_builtin: |
| 283 | boolean = Boolean = bool |
| 284 | # to avoid breaking code which references xmlrpclib.{True,False} |
| 285 | True, False = True, False |
| 286 | else: |
| 287 | class Boolean: |
| 288 | """Boolean-value wrapper. |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 289 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 290 | Use True or False to generate a "boolean" XML-RPC value. |
| 291 | """ |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 292 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 293 | def __init__(self, value = 0): |
| 294 | self.value = operator.truth(value) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 295 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 296 | def encode(self, out): |
| 297 | out.write("<value><boolean>%d</boolean></value>\n" % self.value) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 298 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 299 | def __cmp__(self, other): |
| 300 | if isinstance(other, Boolean): |
| 301 | other = other.value |
| 302 | return cmp(self.value, other) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 303 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 304 | def __repr__(self): |
| 305 | if self.value: |
| 306 | return "<Boolean True at %x>" % id(self) |
| 307 | else: |
| 308 | return "<Boolean False at %x>" % id(self) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 309 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 310 | def __int__(self): |
| 311 | return self.value |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 312 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 313 | def __nonzero__(self): |
| 314 | return self.value |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 315 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 316 | True, False = Boolean(1), Boolean(0) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 317 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 318 | ## |
| 319 | # Map true or false value to XML-RPC boolean values. |
| 320 | # |
| 321 | # @def boolean(value) |
| 322 | # @param value A boolean value. Any true value is mapped to True, |
| 323 | # all other values are mapped to False. |
| 324 | # @return xmlrpclib.True or xmlrpclib.False. |
| 325 | # @see Boolean |
| 326 | # @see True |
| 327 | # @see False |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 328 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 329 | def boolean(value, _truefalse=(False, True)): |
| 330 | """Convert any Python value to XML-RPC 'boolean'.""" |
| 331 | return _truefalse[operator.truth(value)] |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 332 | |
| 333 | ## |
| 334 | # Wrapper for XML-RPC DateTime values. This converts a time value to |
| 335 | # the format used by XML-RPC. |
| 336 | # <p> |
| 337 | # The value can be given as a string in the format |
| 338 | # "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by |
| 339 | # time.localtime()), or an integer value (as returned by time.time()). |
| 340 | # The wrapper uses time.localtime() to convert an integer to a time |
| 341 | # tuple. |
| 342 | # |
| 343 | # @param value The time, given as an ISO 8601 string, a time |
| 344 | # tuple, or a integer time value. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 345 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 346 | class DateTime: |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 347 | """DateTime wrapper for an ISO 8601 string or time tuple or |
| 348 | localtime integer value to generate 'dateTime.iso8601' XML-RPC |
| 349 | value. |
| 350 | """ |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 351 | |
| 352 | def __init__(self, value=0): |
Fredrik Lundh | 78eedce | 2001-08-23 20:04:33 +0000 | [diff] [blame] | 353 | if not isinstance(value, StringType): |
Gustavo Niemeyer | d5b8090 | 2003-06-16 02:49:42 +0000 | [diff] [blame] | 354 | if not isinstance(value, (TupleType, time.struct_time)): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 355 | if value == 0: |
| 356 | value = time.time() |
| 357 | value = time.localtime(value) |
| 358 | value = time.strftime("%Y%m%dT%H:%M:%S", value) |
| 359 | self.value = value |
| 360 | |
| 361 | def __cmp__(self, other): |
| 362 | if isinstance(other, DateTime): |
| 363 | other = other.value |
| 364 | return cmp(self.value, other) |
| 365 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 366 | ## |
| 367 | # Get date/time value. |
| 368 | # |
| 369 | # @return Date/time value, as an ISO 8601 string. |
| 370 | |
| 371 | def __str__(self): |
| 372 | return self.value |
| 373 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 374 | def __repr__(self): |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 375 | return "<DateTime %s at %x>" % (repr(self.value), id(self)) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 376 | |
| 377 | def decode(self, data): |
| 378 | self.value = string.strip(data) |
| 379 | |
| 380 | def encode(self, out): |
| 381 | out.write("<value><dateTime.iso8601>") |
| 382 | out.write(self.value) |
| 383 | out.write("</dateTime.iso8601></value>\n") |
| 384 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 385 | def _datetime(data): |
| 386 | # decode xml element contents into a DateTime structure. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 387 | value = DateTime() |
| 388 | value.decode(data) |
| 389 | return value |
| 390 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 391 | ## |
| 392 | # Wrapper for binary data. This can be used to transport any kind |
| 393 | # of binary data over XML-RPC, using BASE64 encoding. |
| 394 | # |
| 395 | # @param data An 8-bit string containing arbitrary data. |
| 396 | |
Skip Montanaro | bfcbfa7 | 2003-04-24 19:51:31 +0000 | [diff] [blame] | 397 | import base64 |
| 398 | try: |
| 399 | import cStringIO as StringIO |
| 400 | except ImportError: |
| 401 | import StringIO |
| 402 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 403 | class Binary: |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 404 | """Wrapper for binary data.""" |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 405 | |
| 406 | def __init__(self, data=None): |
| 407 | self.data = data |
| 408 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 409 | ## |
| 410 | # Get buffer contents. |
| 411 | # |
| 412 | # @return Buffer contents, as an 8-bit string. |
| 413 | |
| 414 | def __str__(self): |
| 415 | return self.data or "" |
| 416 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 417 | def __cmp__(self, other): |
| 418 | if isinstance(other, Binary): |
| 419 | other = other.data |
| 420 | return cmp(self.data, other) |
| 421 | |
| 422 | def decode(self, data): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 423 | self.data = base64.decodestring(data) |
| 424 | |
| 425 | def encode(self, out): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 426 | out.write("<value><base64>\n") |
| 427 | base64.encode(StringIO.StringIO(self.data), out) |
| 428 | out.write("</base64></value>\n") |
| 429 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 430 | def _binary(data): |
| 431 | # decode xml element contents into a Binary structure |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 432 | value = Binary() |
| 433 | value.decode(data) |
| 434 | return value |
| 435 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 436 | WRAPPERS = (DateTime, Binary) |
| 437 | if not _bool_is_builtin: |
| 438 | WRAPPERS = WRAPPERS + (Boolean,) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 439 | |
| 440 | # -------------------------------------------------------------------- |
| 441 | # XML parsers |
| 442 | |
| 443 | try: |
| 444 | # optional xmlrpclib accelerator. for more information on this |
| 445 | # component, contact info@pythonware.com |
| 446 | import _xmlrpclib |
| 447 | FastParser = _xmlrpclib.Parser |
| 448 | FastUnmarshaller = _xmlrpclib.Unmarshaller |
| 449 | except (AttributeError, ImportError): |
| 450 | FastParser = FastUnmarshaller = None |
| 451 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 452 | try: |
| 453 | import _xmlrpclib |
| 454 | FastMarshaller = _xmlrpclib.Marshaller |
| 455 | except (AttributeError, ImportError): |
| 456 | FastMarshaller = None |
| 457 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 458 | # |
| 459 | # the SGMLOP parser is about 15x faster than Python's builtin |
| 460 | # XML parser. SGMLOP sources can be downloaded from: |
| 461 | # |
| 462 | # http://www.pythonware.com/products/xml/sgmlop.htm |
| 463 | # |
| 464 | |
| 465 | try: |
| 466 | import sgmlop |
| 467 | if not hasattr(sgmlop, "XMLParser"): |
| 468 | raise ImportError |
| 469 | except ImportError: |
| 470 | SgmlopParser = None # sgmlop accelerator not available |
| 471 | else: |
| 472 | class SgmlopParser: |
| 473 | def __init__(self, target): |
| 474 | |
| 475 | # setup callbacks |
| 476 | self.finish_starttag = target.start |
| 477 | self.finish_endtag = target.end |
| 478 | self.handle_data = target.data |
| 479 | self.handle_xml = target.xml |
| 480 | |
| 481 | # activate parser |
| 482 | self.parser = sgmlop.XMLParser() |
| 483 | self.parser.register(self) |
| 484 | self.feed = self.parser.feed |
| 485 | self.entity = { |
| 486 | "amp": "&", "gt": ">", "lt": "<", |
| 487 | "apos": "'", "quot": '"' |
| 488 | } |
| 489 | |
| 490 | def close(self): |
| 491 | try: |
| 492 | self.parser.close() |
| 493 | finally: |
| 494 | self.parser = self.feed = None # nuke circular reference |
| 495 | |
| 496 | def handle_proc(self, tag, attr): |
| 497 | m = re.search("encoding\s*=\s*['\"]([^\"']+)[\"']", attr) |
| 498 | if m: |
| 499 | self.handle_xml(m.group(1), 1) |
| 500 | |
| 501 | def handle_entityref(self, entity): |
| 502 | # <string> entity |
| 503 | try: |
| 504 | self.handle_data(self.entity[entity]) |
| 505 | except KeyError: |
| 506 | self.handle_data("&%s;" % entity) |
| 507 | |
| 508 | try: |
| 509 | from xml.parsers import expat |
Guido van Rossum | b855134 | 2001-10-02 18:33:11 +0000 | [diff] [blame] | 510 | if not hasattr(expat, "ParserCreate"): |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 511 | raise ImportError |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 512 | except ImportError: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 513 | ExpatParser = None # expat not available |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 514 | else: |
| 515 | class ExpatParser: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 516 | # fast expat parser for Python 2.0 and later. this is about |
| 517 | # 50% slower than sgmlop, on roundtrip testing |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 518 | def __init__(self, target): |
| 519 | self._parser = parser = expat.ParserCreate(None, None) |
| 520 | self._target = target |
| 521 | parser.StartElementHandler = target.start |
| 522 | parser.EndElementHandler = target.end |
| 523 | parser.CharacterDataHandler = target.data |
| 524 | encoding = None |
| 525 | if not parser.returns_unicode: |
| 526 | encoding = "utf-8" |
| 527 | target.xml(encoding, None) |
| 528 | |
| 529 | def feed(self, data): |
| 530 | self._parser.Parse(data, 0) |
| 531 | |
| 532 | def close(self): |
| 533 | self._parser.Parse("", 1) # end of data |
| 534 | del self._target, self._parser # get rid of circular references |
| 535 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 536 | class SlowParser: |
| 537 | """Default XML parser (based on xmllib.XMLParser).""" |
| 538 | # this is about 10 times slower than sgmlop, on roundtrip |
| 539 | # testing. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 540 | def __init__(self, target): |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 541 | import xmllib # lazy subclassing (!) |
| 542 | if xmllib.XMLParser not in SlowParser.__bases__: |
| 543 | SlowParser.__bases__ = (xmllib.XMLParser,) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 544 | self.handle_xml = target.xml |
| 545 | self.unknown_starttag = target.start |
| 546 | self.handle_data = target.data |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 547 | self.handle_cdata = target.data |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 548 | self.unknown_endtag = target.end |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 549 | try: |
| 550 | xmllib.XMLParser.__init__(self, accept_utf8=1) |
| 551 | except TypeError: |
| 552 | xmllib.XMLParser.__init__(self) # pre-2.0 |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 553 | |
| 554 | # -------------------------------------------------------------------- |
| 555 | # XML-RPC marshalling and unmarshalling code |
| 556 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 557 | ## |
| 558 | # XML-RPC marshaller. |
| 559 | # |
| 560 | # @param encoding Default encoding for 8-bit strings. The default |
| 561 | # value is None (interpreted as UTF-8). |
| 562 | # @see dumps |
| 563 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 564 | class Marshaller: |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 565 | """Generate an XML-RPC params chunk from a Python data structure. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 566 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 567 | Create a Marshaller instance for each set of parameters, and use |
| 568 | the "dumps" method to convert your data (represented as a tuple) |
| 569 | to an XML-RPC params chunk. To write a fault response, pass a |
| 570 | Fault instance instead. You may prefer to use the "dumps" module |
| 571 | function for this purpose. |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 572 | """ |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 573 | |
| 574 | # by the way, if you don't understand what's going on in here, |
| 575 | # that's perfectly ok. |
| 576 | |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 577 | def __init__(self, encoding=None, allow_none=0): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 578 | self.memo = {} |
| 579 | self.data = None |
| 580 | self.encoding = encoding |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 581 | self.allow_none = allow_none |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 582 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 583 | dispatch = {} |
| 584 | |
| 585 | def dumps(self, values): |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 586 | out = [] |
| 587 | write = out.append |
| 588 | dump = self.__dump |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 589 | if isinstance(values, Fault): |
| 590 | # fault instance |
| 591 | write("<fault>\n") |
Martin v. Löwis | 541342f | 2003-07-12 07:53:04 +0000 | [diff] [blame] | 592 | dump({'faultCode': values.faultCode, |
| 593 | 'faultString': values.faultString}, |
| 594 | write) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 595 | write("</fault>\n") |
| 596 | else: |
| 597 | # parameter block |
Fredrik Lundh | c266bb0 | 2001-08-23 20:13:08 +0000 | [diff] [blame] | 598 | # FIXME: the xml-rpc specification allows us to leave out |
| 599 | # the entire <params> block if there are no parameters. |
| 600 | # however, changing this may break older code (including |
| 601 | # old versions of xmlrpclib.py), so this is better left as |
| 602 | # is for now. See @XMLRPC3 for more information. /F |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 603 | write("<params>\n") |
| 604 | for v in values: |
| 605 | write("<param>\n") |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 606 | dump(v, write) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 607 | write("</param>\n") |
| 608 | write("</params>\n") |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 609 | result = string.join(out, "") |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 610 | return result |
| 611 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 612 | def __dump(self, value, write): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 613 | try: |
| 614 | f = self.dispatch[type(value)] |
| 615 | except KeyError: |
| 616 | raise TypeError, "cannot marshal %s objects" % type(value) |
| 617 | else: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 618 | f(self, value, write) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 619 | |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 620 | def dump_nil (self, value, write): |
| 621 | if not self.allow_none: |
| 622 | raise TypeError, "cannot marshal None unless allow_none is enabled" |
| 623 | write("<value><nil/></value>") |
| 624 | dispatch[NoneType] = dump_nil |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 625 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 626 | def dump_int(self, value, write): |
Skip Montanaro | 5449e08 | 2001-10-17 22:53:33 +0000 | [diff] [blame] | 627 | # in case ints are > 32 bits |
| 628 | if value > MAXINT or value < MININT: |
| 629 | raise OverflowError, "int exceeds XML-RPC limits" |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 630 | write("<value><int>") |
| 631 | write(str(value)) |
| 632 | write("</int></value>\n") |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 633 | dispatch[IntType] = dump_int |
| 634 | |
Skip Montanaro | 9a7c96a | 2003-01-22 18:17:25 +0000 | [diff] [blame] | 635 | if _bool_is_builtin: |
| 636 | def dump_bool(self, value, write): |
| 637 | write("<value><boolean>") |
| 638 | write(value and "1" or "0") |
| 639 | write("</boolean></value>\n") |
| 640 | dispatch[bool] = dump_bool |
| 641 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 642 | def dump_long(self, value, write): |
Skip Montanaro | 5449e08 | 2001-10-17 22:53:33 +0000 | [diff] [blame] | 643 | if value > MAXINT or value < MININT: |
| 644 | raise OverflowError, "long int exceeds XML-RPC limits" |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 645 | write("<value><int>") |
| 646 | write(str(int(value))) |
| 647 | write("</int></value>\n") |
Skip Montanaro | 5e9c71b | 2001-10-10 15:56:34 +0000 | [diff] [blame] | 648 | dispatch[LongType] = dump_long |
| 649 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 650 | def dump_double(self, value, write): |
| 651 | write("<value><double>") |
| 652 | write(repr(value)) |
| 653 | write("</double></value>\n") |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 654 | dispatch[FloatType] = dump_double |
| 655 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 656 | def dump_string(self, value, write, escape=escape): |
| 657 | write("<value><string>") |
| 658 | write(escape(value)) |
| 659 | write("</string></value>\n") |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 660 | dispatch[StringType] = dump_string |
| 661 | |
| 662 | if unicode: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 663 | def dump_unicode(self, value, write, escape=escape): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 664 | value = value.encode(self.encoding) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 665 | write("<value><string>") |
| 666 | write(escape(value)) |
| 667 | write("</string></value>\n") |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 668 | dispatch[UnicodeType] = dump_unicode |
| 669 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 670 | def dump_array(self, value, write): |
| 671 | i = id(value) |
| 672 | if self.memo.has_key(i): |
| 673 | raise TypeError, "cannot marshal recursive sequences" |
| 674 | self.memo[i] = None |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 675 | dump = self.__dump |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 676 | write("<value><array><data>\n") |
| 677 | for v in value: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 678 | dump(v, write) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 679 | write("</data></array></value>\n") |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 680 | del self.memo[i] |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 681 | dispatch[TupleType] = dump_array |
| 682 | dispatch[ListType] = dump_array |
| 683 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 684 | def dump_struct(self, value, write, escape=escape): |
| 685 | i = id(value) |
| 686 | if self.memo.has_key(i): |
| 687 | raise TypeError, "cannot marshal recursive dictionaries" |
| 688 | self.memo[i] = None |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 689 | dump = self.__dump |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 690 | write("<value><struct>\n") |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 691 | for k in value.keys(): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 692 | write("<member>\n") |
| 693 | if type(k) is not StringType: |
| 694 | raise TypeError, "dictionary key must be string" |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 695 | write("<name>%s</name>\n" % escape(k)) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 696 | dump(value[k], write) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 697 | write("</member>\n") |
| 698 | write("</struct></value>\n") |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 699 | del self.memo[i] |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 700 | dispatch[DictType] = dump_struct |
| 701 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 702 | def dump_instance(self, value, write): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 703 | # check for special wrappers |
| 704 | if value.__class__ in WRAPPERS: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 705 | self.write = write |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 706 | value.encode(self) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 707 | del self.write |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 708 | else: |
| 709 | # store instance attributes as a struct (really?) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 710 | self.dump_struct(value.__dict__, write) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 711 | dispatch[InstanceType] = dump_instance |
| 712 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 713 | ## |
| 714 | # XML-RPC unmarshaller. |
| 715 | # |
| 716 | # @see loads |
| 717 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 718 | class Unmarshaller: |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 719 | """Unmarshal an XML-RPC response, based on incoming XML event |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 720 | messages (start, data, end). Call close() to get the resulting |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 721 | data structure. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 722 | |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 723 | Note that this reader is fairly tolerant, and gladly accepts bogus |
| 724 | XML-RPC data without complaining (but not bogus XML). |
Fred Drake | 1b41079 | 2001-09-04 18:55:03 +0000 | [diff] [blame] | 725 | """ |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 726 | |
| 727 | # and again, if you don't understand what's going on in here, |
| 728 | # that's perfectly ok. |
| 729 | |
| 730 | def __init__(self): |
| 731 | self._type = None |
| 732 | self._stack = [] |
| 733 | self._marks = [] |
| 734 | self._data = [] |
| 735 | self._methodname = None |
| 736 | self._encoding = "utf-8" |
| 737 | self.append = self._stack.append |
| 738 | |
| 739 | def close(self): |
| 740 | # return response tuple and target method |
| 741 | if self._type is None or self._marks: |
| 742 | raise ResponseError() |
| 743 | if self._type == "fault": |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 744 | raise Fault(**self._stack[0]) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 745 | return tuple(self._stack) |
| 746 | |
| 747 | def getmethodname(self): |
| 748 | return self._methodname |
| 749 | |
| 750 | # |
| 751 | # event handlers |
| 752 | |
| 753 | def xml(self, encoding, standalone): |
| 754 | self._encoding = encoding |
| 755 | # FIXME: assert standalone == 1 ??? |
| 756 | |
| 757 | def start(self, tag, attrs): |
| 758 | # prepare to handle this element |
| 759 | if tag == "array" or tag == "struct": |
| 760 | self._marks.append(len(self._stack)) |
| 761 | self._data = [] |
| 762 | self._value = (tag == "value") |
| 763 | |
| 764 | def data(self, text): |
| 765 | self._data.append(text) |
| 766 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 767 | def end(self, tag, join=string.join): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 768 | # call the appropriate end tag handler |
| 769 | try: |
| 770 | f = self.dispatch[tag] |
| 771 | except KeyError: |
| 772 | pass # unknown tag ? |
| 773 | else: |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 774 | return f(self, join(self._data, "")) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 775 | |
| 776 | # |
| 777 | # accelerator support |
| 778 | |
| 779 | def end_dispatch(self, tag, data): |
| 780 | # dispatch data |
| 781 | try: |
| 782 | f = self.dispatch[tag] |
| 783 | except KeyError: |
| 784 | pass # unknown tag ? |
| 785 | else: |
| 786 | return f(self, data) |
| 787 | |
| 788 | # |
| 789 | # element decoders |
| 790 | |
| 791 | dispatch = {} |
| 792 | |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 793 | def end_nil (self, data): |
| 794 | self.append(None) |
| 795 | self._value = 0 |
| 796 | dispatch["nil"] = end_nil |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 797 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 798 | def end_boolean(self, data): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 799 | if data == "0": |
| 800 | self.append(False) |
| 801 | elif data == "1": |
| 802 | self.append(True) |
| 803 | else: |
| 804 | raise TypeError, "bad boolean value" |
| 805 | self._value = 0 |
| 806 | dispatch["boolean"] = end_boolean |
| 807 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 808 | def end_int(self, data): |
| 809 | self.append(int(data)) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 810 | self._value = 0 |
| 811 | dispatch["i4"] = end_int |
| 812 | dispatch["int"] = end_int |
| 813 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 814 | def end_double(self, data): |
| 815 | self.append(float(data)) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 816 | self._value = 0 |
| 817 | dispatch["double"] = end_double |
| 818 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 819 | def end_string(self, data): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 820 | if self._encoding: |
| 821 | data = _decode(data, self._encoding) |
| 822 | self.append(_stringify(data)) |
| 823 | self._value = 0 |
| 824 | dispatch["string"] = end_string |
| 825 | dispatch["name"] = end_string # struct keys are always strings |
| 826 | |
| 827 | def end_array(self, data): |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 828 | mark = self._marks.pop() |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 829 | # map arrays to Python lists |
| 830 | self._stack[mark:] = [self._stack[mark:]] |
| 831 | self._value = 0 |
| 832 | dispatch["array"] = end_array |
| 833 | |
| 834 | def end_struct(self, data): |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 835 | mark = self._marks.pop() |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 836 | # map structs to Python dictionaries |
| 837 | dict = {} |
| 838 | items = self._stack[mark:] |
| 839 | for i in range(0, len(items), 2): |
| 840 | dict[_stringify(items[i])] = items[i+1] |
| 841 | self._stack[mark:] = [dict] |
| 842 | self._value = 0 |
| 843 | dispatch["struct"] = end_struct |
| 844 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 845 | def end_base64(self, data): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 846 | value = Binary() |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 847 | value.decode(data) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 848 | self.append(value) |
| 849 | self._value = 0 |
| 850 | dispatch["base64"] = end_base64 |
| 851 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 852 | def end_dateTime(self, data): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 853 | value = DateTime() |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 854 | value.decode(data) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 855 | self.append(value) |
| 856 | dispatch["dateTime.iso8601"] = end_dateTime |
| 857 | |
| 858 | def end_value(self, data): |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 859 | # if we stumble upon a value element with no internal |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 860 | # elements, treat it as a string element |
| 861 | if self._value: |
| 862 | self.end_string(data) |
| 863 | dispatch["value"] = end_value |
| 864 | |
| 865 | def end_params(self, data): |
| 866 | self._type = "params" |
| 867 | dispatch["params"] = end_params |
| 868 | |
| 869 | def end_fault(self, data): |
| 870 | self._type = "fault" |
| 871 | dispatch["fault"] = end_fault |
| 872 | |
Fredrik Lundh | 1538c23 | 2001-10-01 19:42:03 +0000 | [diff] [blame] | 873 | def end_methodName(self, data): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 874 | if self._encoding: |
| 875 | data = _decode(data, self._encoding) |
| 876 | self._methodname = data |
| 877 | self._type = "methodName" # no params |
| 878 | dispatch["methodName"] = end_methodName |
| 879 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 880 | ## Multicall support |
| 881 | # |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 882 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 883 | class _MultiCallMethod: |
| 884 | # some lesser magic to store calls made to a MultiCall object |
| 885 | # for batch execution |
| 886 | def __init__(self, call_list, name): |
| 887 | self.__call_list = call_list |
| 888 | self.__name = name |
| 889 | def __getattr__(self, name): |
| 890 | return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name)) |
| 891 | def __call__(self, *args): |
| 892 | self.__call_list.append((self.__name, args)) |
| 893 | |
| 894 | def MultiCallIterator(results): |
| 895 | """Iterates over the results of a multicall. Exceptions are |
| 896 | thrown in response to xmlrpc faults.""" |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 897 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 898 | for i in results: |
| 899 | if type(i) == type({}): |
| 900 | raise Fault(i['faultCode'], i['faultString']) |
| 901 | elif type(i) == type([]): |
| 902 | yield i[0] |
| 903 | else: |
| 904 | raise ValueError,\ |
| 905 | "unexpected type in multicall result" |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 906 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 907 | class MultiCall: |
| 908 | """server -> a object used to boxcar method calls |
| 909 | |
| 910 | server should be a ServerProxy object. |
| 911 | |
| 912 | Methods can be added to the MultiCall using normal |
| 913 | method call syntax e.g.: |
| 914 | |
| 915 | multicall = MultiCall(server_proxy) |
| 916 | multicall.add(2,3) |
| 917 | multicall.get_address("Guido") |
| 918 | |
| 919 | To execute the multicall, call the MultiCall object e.g.: |
| 920 | |
| 921 | add_result, address = multicall() |
| 922 | """ |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 923 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 924 | def __init__(self, server): |
| 925 | self.__server = server |
| 926 | self.__call_list = [] |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 927 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 928 | def __repr__(self): |
| 929 | return "<MultiCall at %x>" % id(self) |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 930 | |
Martin v. Löwis | 45394c2 | 2003-10-31 13:49:36 +0000 | [diff] [blame] | 931 | __str__ = __repr__ |
| 932 | |
| 933 | def __getattr__(self, name): |
| 934 | return _MultiCallMethod(self.__call_list, name) |
| 935 | |
| 936 | def __call__(self): |
| 937 | marshalled_list = [] |
| 938 | for name, args in self.__call_list: |
| 939 | marshalled_list.append({'methodName' : name, 'params' : args}) |
| 940 | |
| 941 | return MultiCallIterator(self.__server.system.multicall(marshalled_list)) |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 942 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 943 | # -------------------------------------------------------------------- |
| 944 | # convenience functions |
| 945 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 946 | ## |
| 947 | # Create a parser object, and connect it to an unmarshalling instance. |
| 948 | # This function picks the fastest available XML parser. |
| 949 | # |
| 950 | # return A (parser, unmarshaller) tuple. |
| 951 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 952 | def getparser(): |
| 953 | """getparser() -> parser, unmarshaller |
| 954 | |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 955 | Create an instance of the fastest available parser, and attach it |
| 956 | to an unmarshalling object. Return both objects. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 957 | """ |
| 958 | if FastParser and FastUnmarshaller: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 959 | target = FastUnmarshaller(True, False, _binary, _datetime, Fault) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 960 | parser = FastParser(target) |
| 961 | else: |
| 962 | target = Unmarshaller() |
| 963 | if FastParser: |
| 964 | parser = FastParser(target) |
| 965 | elif SgmlopParser: |
| 966 | parser = SgmlopParser(target) |
| 967 | elif ExpatParser: |
| 968 | parser = ExpatParser(target) |
| 969 | else: |
| 970 | parser = SlowParser(target) |
| 971 | return parser, target |
| 972 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 973 | ## |
| 974 | # Convert a Python tuple or a Fault instance to an XML-RPC packet. |
| 975 | # |
| 976 | # @def dumps(params, **options) |
| 977 | # @param params A tuple or Fault instance. |
| 978 | # @keyparam methodname If given, create a methodCall request for |
| 979 | # this method name. |
| 980 | # @keyparam methodresponse If given, create a methodResponse packet. |
| 981 | # If used with a tuple, the tuple must be a singleton (that is, |
| 982 | # it must contain exactly one element). |
| 983 | # @keyparam encoding The packet encoding. |
| 984 | # @return A string containing marshalled data. |
| 985 | |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 986 | def dumps(params, methodname=None, methodresponse=None, encoding=None, |
| 987 | allow_none=0): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 988 | """data [,options] -> marshalled data |
| 989 | |
| 990 | Convert an argument tuple or a Fault instance to an XML-RPC |
| 991 | request (or response, if the methodresponse option is used). |
| 992 | |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 993 | In addition to the data object, the following options can be given |
| 994 | as keyword arguments: |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 995 | |
| 996 | methodname: the method name for a methodCall packet |
| 997 | |
| 998 | methodresponse: true to create a methodResponse packet. |
| 999 | If this option is used with a tuple, the tuple must be |
| 1000 | a singleton (i.e. it can contain only one element). |
| 1001 | |
| 1002 | encoding: the packet encoding (default is UTF-8) |
| 1003 | |
| 1004 | All 8-bit strings in the data structure are assumed to use the |
| 1005 | packet encoding. Unicode strings are automatically converted, |
Fredrik Lundh | b0e8e9b | 2001-09-10 21:45:42 +0000 | [diff] [blame] | 1006 | where necessary. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1007 | """ |
| 1008 | |
| 1009 | assert isinstance(params, TupleType) or isinstance(params, Fault),\ |
| 1010 | "argument must be tuple or Fault instance" |
| 1011 | |
| 1012 | if isinstance(params, Fault): |
| 1013 | methodresponse = 1 |
| 1014 | elif methodresponse and isinstance(params, TupleType): |
| 1015 | assert len(params) == 1, "response tuple must be a singleton" |
| 1016 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1017 | if not encoding: |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1018 | encoding = "utf-8" |
| 1019 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1020 | if FastMarshaller: |
| 1021 | m = FastMarshaller(encoding) |
| 1022 | else: |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 1023 | m = Marshaller(encoding, allow_none) |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1024 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1025 | data = m.dumps(params) |
| 1026 | |
| 1027 | if encoding != "utf-8": |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1028 | xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1029 | else: |
| 1030 | xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default |
| 1031 | |
| 1032 | # standard XML-RPC wrappings |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1033 | if methodname: |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1034 | # a method call |
| 1035 | if not isinstance(methodname, StringType): |
| 1036 | methodname = methodname.encode(encoding) |
| 1037 | data = ( |
| 1038 | xmlheader, |
| 1039 | "<methodCall>\n" |
| 1040 | "<methodName>", methodname, "</methodName>\n", |
| 1041 | data, |
| 1042 | "</methodCall>\n" |
| 1043 | ) |
| 1044 | elif methodresponse: |
| 1045 | # a method response, or a fault structure |
| 1046 | data = ( |
| 1047 | xmlheader, |
| 1048 | "<methodResponse>\n", |
| 1049 | data, |
| 1050 | "</methodResponse>\n" |
| 1051 | ) |
| 1052 | else: |
| 1053 | return data # return as is |
| 1054 | return string.join(data, "") |
| 1055 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1056 | ## |
| 1057 | # Convert an XML-RPC packet to a Python object. If the XML-RPC packet |
| 1058 | # represents a fault condition, this function raises a Fault exception. |
| 1059 | # |
| 1060 | # @param data An XML-RPC packet, given as an 8-bit string. |
Walter Dörwald | f0dfc7a | 2003-10-20 14:01:56 +0000 | [diff] [blame] | 1061 | # @return A tuple containing the unpacked data, and the method name |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1062 | # (None if not present). |
| 1063 | # @see Fault |
| 1064 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1065 | def loads(data): |
| 1066 | """data -> unmarshalled data, method name |
| 1067 | |
| 1068 | Convert an XML-RPC packet to unmarshalled data plus a method |
| 1069 | name (None if not present). |
| 1070 | |
| 1071 | If the XML-RPC packet represents a fault condition, this function |
| 1072 | raises a Fault exception. |
| 1073 | """ |
| 1074 | p, u = getparser() |
| 1075 | p.feed(data) |
| 1076 | p.close() |
| 1077 | return u.close(), u.getmethodname() |
| 1078 | |
| 1079 | |
| 1080 | # -------------------------------------------------------------------- |
| 1081 | # request dispatcher |
| 1082 | |
| 1083 | class _Method: |
| 1084 | # some magic to bind an XML-RPC method to an RPC server. |
| 1085 | # supports "nested" methods (e.g. examples.getStateName) |
| 1086 | def __init__(self, send, name): |
| 1087 | self.__send = send |
| 1088 | self.__name = name |
| 1089 | def __getattr__(self, name): |
| 1090 | return _Method(self.__send, "%s.%s" % (self.__name, name)) |
| 1091 | def __call__(self, *args): |
| 1092 | return self.__send(self.__name, args) |
| 1093 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1094 | ## |
| 1095 | # Standard transport class for XML-RPC over HTTP. |
| 1096 | # <p> |
| 1097 | # You can create custom transports by subclassing this method, and |
| 1098 | # overriding selected methods. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1099 | |
| 1100 | class Transport: |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 1101 | """Handles an HTTP transaction to an XML-RPC server.""" |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1102 | |
| 1103 | # client identifier (may be overridden) |
| 1104 | user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__ |
| 1105 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1106 | ## |
| 1107 | # Send a complete request, and parse the response. |
| 1108 | # |
| 1109 | # @param host Target host. |
| 1110 | # @param handler Target PRC handler. |
| 1111 | # @param request_body XML-RPC request body. |
| 1112 | # @param verbose Debugging flag. |
| 1113 | # @return Parsed response. |
| 1114 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1115 | def request(self, host, handler, request_body, verbose=0): |
| 1116 | # issue XML-RPC request |
| 1117 | |
| 1118 | h = self.make_connection(host) |
| 1119 | if verbose: |
| 1120 | h.set_debuglevel(1) |
| 1121 | |
| 1122 | self.send_request(h, handler, request_body) |
| 1123 | self.send_host(h, host) |
| 1124 | self.send_user_agent(h) |
| 1125 | self.send_content(h, request_body) |
| 1126 | |
| 1127 | errcode, errmsg, headers = h.getreply() |
| 1128 | |
| 1129 | if errcode != 200: |
| 1130 | raise ProtocolError( |
| 1131 | host + handler, |
| 1132 | errcode, errmsg, |
| 1133 | headers |
| 1134 | ) |
| 1135 | |
| 1136 | self.verbose = verbose |
| 1137 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1138 | try: |
| 1139 | sock = h._conn.sock |
| 1140 | except AttributeError: |
| 1141 | sock = None |
| 1142 | |
| 1143 | return self._parse_response(h.getfile(), sock) |
| 1144 | |
| 1145 | ## |
| 1146 | # Create parser. |
| 1147 | # |
| 1148 | # @return A 2-tuple containing a parser and a unmarshaller. |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1149 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 1150 | def getparser(self): |
| 1151 | # get parser and unmarshaller |
| 1152 | return getparser() |
| 1153 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1154 | ## |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1155 | # Get authorization info from host parameter |
| 1156 | # Host may be a string, or a (host, x509-dict) tuple; if a string, |
| 1157 | # it is checked for a "user:pw@host" format, and a "Basic |
| 1158 | # Authentication" header is added if appropriate. |
| 1159 | # |
| 1160 | # @param host Host descriptor (URL or (URL, x509 info) tuple). |
| 1161 | # @return A 3-tuple containing (actual host, extra headers, |
| 1162 | # x509 info). The header and x509 fields may be None. |
| 1163 | |
| 1164 | def get_host_info(self, host): |
| 1165 | |
| 1166 | x509 = {} |
| 1167 | if isinstance(host, TupleType): |
| 1168 | host, x509 = host |
| 1169 | |
| 1170 | import urllib |
| 1171 | auth, host = urllib.splituser(host) |
| 1172 | |
| 1173 | if auth: |
| 1174 | import base64 |
Fredrik Lundh | 768c98b | 2002-11-01 17:14:16 +0000 | [diff] [blame] | 1175 | auth = base64.encodestring(urllib.unquote(auth)) |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1176 | auth = string.join(string.split(auth), "") # get rid of whitespace |
| 1177 | extra_headers = [ |
| 1178 | ("Authorization", "Basic " + auth) |
| 1179 | ] |
| 1180 | else: |
| 1181 | extra_headers = None |
| 1182 | |
| 1183 | return host, extra_headers, x509 |
| 1184 | |
| 1185 | ## |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1186 | # Connect to server. |
| 1187 | # |
| 1188 | # @param host Target host. |
| 1189 | # @return A connection handle. |
| 1190 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1191 | def make_connection(self, host): |
| 1192 | # create a HTTP connection object from a host descriptor |
| 1193 | import httplib |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1194 | host, extra_headers, x509 = self.get_host_info(host) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1195 | return httplib.HTTP(host) |
| 1196 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1197 | ## |
| 1198 | # Send request header. |
| 1199 | # |
| 1200 | # @param connection Connection handle. |
| 1201 | # @param handler Target RPC handler. |
| 1202 | # @param request_body XML-RPC body. |
| 1203 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1204 | def send_request(self, connection, handler, request_body): |
| 1205 | connection.putrequest("POST", handler) |
| 1206 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1207 | ## |
| 1208 | # Send host name. |
| 1209 | # |
| 1210 | # @param connection Connection handle. |
| 1211 | # @param host Host name. |
| 1212 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1213 | def send_host(self, connection, host): |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1214 | host, extra_headers, x509 = self.get_host_info(host) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1215 | connection.putheader("Host", host) |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1216 | if extra_headers: |
| 1217 | if isinstance(extra_headers, DictType): |
| 1218 | extra_headers = extra_headers.items() |
| 1219 | for key, value in extra_headers: |
| 1220 | connection.putheader(key, value) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1221 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1222 | ## |
| 1223 | # Send user-agent identifier. |
| 1224 | # |
| 1225 | # @param connection Connection handle. |
| 1226 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1227 | def send_user_agent(self, connection): |
| 1228 | connection.putheader("User-Agent", self.user_agent) |
| 1229 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1230 | ## |
| 1231 | # Send request body. |
| 1232 | # |
| 1233 | # @param connection Connection handle. |
| 1234 | # @param request_body XML-RPC request body. |
| 1235 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1236 | def send_content(self, connection, request_body): |
| 1237 | connection.putheader("Content-Type", "text/xml") |
| 1238 | connection.putheader("Content-Length", str(len(request_body))) |
| 1239 | connection.endheaders() |
| 1240 | if request_body: |
| 1241 | connection.send(request_body) |
| 1242 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1243 | ## |
| 1244 | # Parse response. |
| 1245 | # |
| 1246 | # @param file Stream. |
| 1247 | # @return Response tuple and target method. |
| 1248 | |
| 1249 | def parse_response(self, file): |
| 1250 | # compatibility interface |
| 1251 | return self._parse_response(file, None) |
| 1252 | |
| 1253 | ## |
| 1254 | # Parse response (alternate interface). This is similar to the |
| 1255 | # parse_response method, but also provides direct access to the |
| 1256 | # underlying socket object (where available). |
| 1257 | # |
| 1258 | # @param file Stream. |
| 1259 | # @param sock Socket handle (or None, if the socket object |
| 1260 | # could not be accessed). |
| 1261 | # @return Response tuple and target method. |
| 1262 | |
| 1263 | def _parse_response(self, file, sock): |
| 1264 | # read response from input file/socket, and parse it |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1265 | |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 1266 | p, u = self.getparser() |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1267 | |
| 1268 | while 1: |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1269 | if sock: |
| 1270 | response = sock.recv(1024) |
| 1271 | else: |
| 1272 | response = file.read(1024) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1273 | if not response: |
| 1274 | break |
| 1275 | if self.verbose: |
| 1276 | print "body:", repr(response) |
| 1277 | p.feed(response) |
| 1278 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1279 | file.close() |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1280 | p.close() |
| 1281 | |
| 1282 | return u.close() |
| 1283 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1284 | ## |
| 1285 | # Standard transport class for XML-RPC over HTTPS. |
| 1286 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1287 | class SafeTransport(Transport): |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 1288 | """Handles an HTTPS transaction to an XML-RPC server.""" |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1289 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1290 | # FIXME: mostly untested |
| 1291 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1292 | def make_connection(self, host): |
| 1293 | # create a HTTPS connection object from a host descriptor |
| 1294 | # host may be a string, or a (host, x509-dict) tuple |
| 1295 | import httplib |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1296 | host, extra_headers, x509 = self.get_host_info(host) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1297 | try: |
| 1298 | HTTPS = httplib.HTTPS |
| 1299 | except AttributeError: |
Fredrik Lundh | 1303c7c | 2002-10-22 18:23:00 +0000 | [diff] [blame] | 1300 | raise NotImplementedError( |
| 1301 | "your version of httplib doesn't support HTTPS" |
| 1302 | ) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1303 | else: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 1304 | return HTTPS(host, None, **(x509 or {})) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1305 | |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1306 | ## |
| 1307 | # Standard server proxy. This class establishes a virtual connection |
| 1308 | # to an XML-RPC server. |
| 1309 | # <p> |
| 1310 | # This class is available as ServerProxy and Server. New code should |
| 1311 | # use ServerProxy, to avoid confusion. |
| 1312 | # |
| 1313 | # @def ServerProxy(uri, **options) |
| 1314 | # @param uri The connection point on the server. |
| 1315 | # @keyparam transport A transport factory, compatible with the |
| 1316 | # standard transport class. |
| 1317 | # @keyparam encoding The default encoding used for 8-bit strings |
| 1318 | # (default is UTF-8). |
| 1319 | # @keyparam verbose Use a true value to enable debugging output. |
| 1320 | # (printed to standard output). |
| 1321 | # @see Transport |
| 1322 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1323 | class ServerProxy: |
| 1324 | """uri [,options] -> a logical connection to an XML-RPC server |
| 1325 | |
| 1326 | uri is the connection point on the server, given as |
| 1327 | scheme://host/target. |
| 1328 | |
| 1329 | The standard implementation always supports the "http" scheme. If |
| 1330 | SSL socket support is available (Python 2.0), it also supports |
| 1331 | "https". |
| 1332 | |
| 1333 | If the target part and the slash preceding it are both omitted, |
| 1334 | "/RPC2" is assumed. |
| 1335 | |
| 1336 | The following options can be given as keyword arguments: |
| 1337 | |
| 1338 | transport: a transport factory |
| 1339 | encoding: the request encoding (default is UTF-8) |
| 1340 | |
| 1341 | All 8-bit strings passed to the server proxy are assumed to use |
| 1342 | the given encoding. |
| 1343 | """ |
| 1344 | |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 1345 | def __init__(self, uri, transport=None, encoding=None, verbose=0, |
| 1346 | allow_none=0): |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1347 | # establish a "logical" server connection |
| 1348 | |
| 1349 | # get the url |
Fredrik Lundh | c4c062f | 2001-09-10 19:45:02 +0000 | [diff] [blame] | 1350 | import urllib |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1351 | type, uri = urllib.splittype(uri) |
| 1352 | if type not in ("http", "https"): |
| 1353 | raise IOError, "unsupported XML-RPC protocol" |
| 1354 | self.__host, self.__handler = urllib.splithost(uri) |
| 1355 | if not self.__handler: |
| 1356 | self.__handler = "/RPC2" |
| 1357 | |
| 1358 | if transport is None: |
| 1359 | if type == "https": |
| 1360 | transport = SafeTransport() |
| 1361 | else: |
| 1362 | transport = Transport() |
| 1363 | self.__transport = transport |
| 1364 | |
| 1365 | self.__encoding = encoding |
| 1366 | self.__verbose = verbose |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 1367 | self.__allow_none = allow_none |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 1368 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1369 | def __request(self, methodname, params): |
| 1370 | # call a method on the remote server |
| 1371 | |
Andrew M. Kuchling | a4c2b74 | 2003-04-25 00:26:51 +0000 | [diff] [blame] | 1372 | request = dumps(params, methodname, encoding=self.__encoding, |
| 1373 | allow_none=self.__allow_none) |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1374 | |
| 1375 | response = self.__transport.request( |
| 1376 | self.__host, |
| 1377 | self.__handler, |
| 1378 | request, |
| 1379 | verbose=self.__verbose |
| 1380 | ) |
| 1381 | |
| 1382 | if len(response) == 1: |
| 1383 | response = response[0] |
| 1384 | |
| 1385 | return response |
| 1386 | |
| 1387 | def __repr__(self): |
| 1388 | return ( |
Fredrik Lundh | 78eedce | 2001-08-23 20:04:33 +0000 | [diff] [blame] | 1389 | "<ServerProxy for %s%s>" % |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1390 | (self.__host, self.__handler) |
| 1391 | ) |
| 1392 | |
| 1393 | __str__ = __repr__ |
Raymond Hettinger | cc523fc | 2003-11-02 09:47:05 +0000 | [diff] [blame] | 1394 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1395 | def __getattr__(self, name): |
| 1396 | # magic method dispatcher |
| 1397 | return _Method(self.__request, name) |
| 1398 | |
| 1399 | # note: to call a remote object with an non-standard name, use |
| 1400 | # result getattr(server, "strange-python-name")(args) |
| 1401 | |
Fredrik Lundh | 78eedce | 2001-08-23 20:04:33 +0000 | [diff] [blame] | 1402 | # compatibility |
Fredrik Lundh | 3d9addd | 2002-06-27 21:36:21 +0000 | [diff] [blame] | 1403 | |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1404 | Server = ServerProxy |
| 1405 | |
| 1406 | # -------------------------------------------------------------------- |
| 1407 | # test code |
| 1408 | |
| 1409 | if __name__ == "__main__": |
| 1410 | |
| 1411 | # simple test program (from the XML-RPC specification) |
| 1412 | |
Fredrik Lundh | 78eedce | 2001-08-23 20:04:33 +0000 | [diff] [blame] | 1413 | # server = ServerProxy("http://localhost:8000") # local server |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 1414 | server = ServerProxy("http://betty.userland.com") |
Fredrik Lundh | b905633 | 2001-07-11 17:42:21 +0000 | [diff] [blame] | 1415 | |
| 1416 | print server |
| 1417 | |
| 1418 | try: |
| 1419 | print server.examples.getStateName(41) |
| 1420 | except Error, v: |
| 1421 | print "ERROR", v |