blob: 2466e25fe9d78418b6331cbc726d7e1e7408d1a9 [file] [log] [blame]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001#
2# XML-RPC CLIENT LIBRARY
3# $Id$
4#
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00005# 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 Lundhb9056332001-07-11 17:42:21 +000016# 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 Lundh78eedce2001-08-23 20:04:33 +000030# 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 Lundhc4c062f2001-09-10 19:45:02 +000032# 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 Lundh1538c232001-10-01 19:42:03 +000034# 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 Lundh3d9addd2002-06-27 21:36:21 +000036# 2001-10-02 fl More dumps microtuning
37# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
Skip Montanaro5e9c71b2001-10-10 15:56:34 +000038# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000039# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
Fredrik Lundhb6ab93f2001-12-19 21:40:04 +000040# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000041# 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 Lundh1303c7c2002-10-22 18:23:00 +000046# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
Martin v. Löwis541342f2003-07-12 07:53:04 +000047# 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öwis45394c22003-10-31 13:49:36 +000053# 2003-10-31 mvl Add multicall support
Fredrik Lundhb9056332001-07-11 17:42:21 +000054#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000055# Copyright (c) 1999-2002 by Secret Labs AB.
56# Copyright (c) 1999-2002 by Fredrik Lundh.
Fredrik Lundhb9056332001-07-11 17:42:21 +000057#
58# info@pythonware.com
59# http://www.pythonware.com
60#
61# --------------------------------------------------------------------
62# The XML-RPC client interface is
63#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000064# Copyright (c) 1999-2002 by Secret Labs AB
65# Copyright (c) 1999-2002 by Fredrik Lundh
Fredrik Lundhb9056332001-07-11 17:42:21 +000066#
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 Lundh3d9addd2002-06-27 21:36:21 +000091# things to look into some day:
Fredrik Lundhb9056332001-07-11 17:42:21 +000092
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000093# TODO: sort out True/False/boolean issues for Python 2.3
Fredrik Lundhb9056332001-07-11 17:42:21 +000094
Fred Drake1b410792001-09-04 18:55:03 +000095"""
96An XML-RPC client interface for Python.
97
98The marshalling and response parser code can also be used to
99implement XML-RPC servers.
100
Fred Drake1b410792001-09-04 18:55:03 +0000101Exported exceptions:
102
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000103 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 Drake1b410792001-09-04 18:55:03 +0000107
108Exported classes:
109
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000110 ServerProxy Represents a logical connection to an XML-RPC server
Fred Drake1b410792001-09-04 18:55:03 +0000111
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000112 MultiCall Executor of boxcared xmlrpc requests
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000113 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 Drake1b410792001-09-04 18:55:03 +0000118
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000119 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 Drake1b410792001-09-04 18:55:03 +0000124
125Exported constants:
126
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000127 True
128 False
Fred Drake1b410792001-09-04 18:55:03 +0000129
130Exported functions:
131
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000132 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 Drake1b410792001-09-04 18:55:03 +0000139"""
140
Fred Drake2a2d9702001-10-17 01:51:04 +0000141import re, string, time, operator
Fredrik Lundh1538c232001-10-01 19:42:03 +0000142
Fredrik Lundhb9056332001-07-11 17:42:21 +0000143from types import *
Fredrik Lundhb9056332001-07-11 17:42:21 +0000144
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000145# --------------------------------------------------------------------
146# Internal stuff
147
Fredrik Lundhb9056332001-07-11 17:42:21 +0000148try:
149 unicode
150except NameError:
151 unicode = None # unicode support not available
152
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000153try:
154 _bool_is_builtin = False.__class__.__name__ == "bool"
155except NameError:
156 _bool_is_builtin = 0
157
Fredrik Lundhb9056332001-07-11 17:42:21 +0000158def _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 Lundh1538c232001-10-01 19:42:03 +0000164def escape(s, replace=string.replace):
165 s = replace(s, "&", "&")
166 s = replace(s, "<", "&lt;")
167 return replace(s, ">", "&gt;",)
168
Fredrik Lundhb9056332001-07-11 17:42:21 +0000169if 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
176else:
177 def _stringify(string):
178 return string
179
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000180__version__ = "1.0.1"
181
182# xmlrpc integer limits
183MAXINT = 2L**31-1
184MININT = -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
191PARSE_ERROR = -32700
192SERVER_ERROR = -32600
193APPLICATION_ERROR = -32500
194SYSTEM_ERROR = -32400
195TRANSPORT_ERROR = -32300
196
197# Specific errors
198NOT_WELLFORMED_ERROR = -32700
199UNSUPPORTED_ENCODING = -32701
200INVALID_ENCODING_CHAR = -32702
201INVALID_XMLRPC = -32600
202METHOD_NOT_FOUND = -32601
203INVALID_METHOD_PARAMS = -32602
204INTERNAL_ERROR = -32603
Fredrik Lundhb9056332001-07-11 17:42:21 +0000205
206# --------------------------------------------------------------------
207# Exceptions
208
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000209##
210# Base class for all kinds of client-side errors.
211
Fredrik Lundh78eedce2001-08-23 20:04:33 +0000212class Error(Exception):
Fred Drake1b410792001-09-04 18:55:03 +0000213 """Base class for client errors."""
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000214 def __str__(self):
215 return repr(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000216
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000217##
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 Lundhb9056332001-07-11 17:42:21 +0000227class ProtocolError(Error):
Fred Drake1b410792001-09-04 18:55:03 +0000228 """Indicates an HTTP protocol error."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000229 def __init__(self, url, errcode, errmsg, headers):
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000230 Error.__init__(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000231 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 Lundh3d9addd2002-06-27 21:36:21 +0000241##
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 Lundhb9056332001-07-11 17:42:21 +0000246class ResponseError(Error):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000247 """Indicates a broken response package."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000248 pass
249
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000250##
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 Lundhb9056332001-07-11 17:42:21 +0000259class Fault(Error):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000260 """Indicates an XML-RPC fault package."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000261 def __init__(self, faultCode, faultString, **extra):
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000262 Error.__init__(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000263 self.faultCode = faultCode
264 self.faultString = faultString
265 def __repr__(self):
266 return (
267 "<Fault %s: %s>" %
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000268 (self.faultCode, repr(self.faultString))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000269 )
270
271# --------------------------------------------------------------------
272# Special values
273
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000274##
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 Montanaro9a7c96a2003-01-22 18:17:25 +0000282if _bool_is_builtin:
283 boolean = Boolean = bool
284 # to avoid breaking code which references xmlrpclib.{True,False}
285 True, False = True, False
286else:
287 class Boolean:
288 """Boolean-value wrapper.
Fred Drake1b410792001-09-04 18:55:03 +0000289
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000290 Use True or False to generate a "boolean" XML-RPC value.
291 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000292
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000293 def __init__(self, value = 0):
294 self.value = operator.truth(value)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000295
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000296 def encode(self, out):
297 out.write("<value><boolean>%d</boolean></value>\n" % self.value)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000298
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000299 def __cmp__(self, other):
300 if isinstance(other, Boolean):
301 other = other.value
302 return cmp(self.value, other)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000303
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000304 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 Lundhb9056332001-07-11 17:42:21 +0000309
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000310 def __int__(self):
311 return self.value
Fredrik Lundhb9056332001-07-11 17:42:21 +0000312
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000313 def __nonzero__(self):
314 return self.value
Fredrik Lundhb9056332001-07-11 17:42:21 +0000315
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000316 True, False = Boolean(1), Boolean(0)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000317
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000318 ##
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 Lundh3d9addd2002-06-27 21:36:21 +0000328
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000329 def boolean(value, _truefalse=(False, True)):
330 """Convert any Python value to XML-RPC 'boolean'."""
331 return _truefalse[operator.truth(value)]
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000332
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 Lundhb9056332001-07-11 17:42:21 +0000345
Fredrik Lundhb9056332001-07-11 17:42:21 +0000346class DateTime:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000347 """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 Lundhb9056332001-07-11 17:42:21 +0000351
352 def __init__(self, value=0):
Fredrik Lundh78eedce2001-08-23 20:04:33 +0000353 if not isinstance(value, StringType):
Gustavo Niemeyerd5b80902003-06-16 02:49:42 +0000354 if not isinstance(value, (TupleType, time.struct_time)):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000355 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 Lundh3d9addd2002-06-27 21:36:21 +0000366 ##
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 Lundhb9056332001-07-11 17:42:21 +0000374 def __repr__(self):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000375 return "<DateTime %s at %x>" % (repr(self.value), id(self))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000376
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 Lundh3d9addd2002-06-27 21:36:21 +0000385def _datetime(data):
386 # decode xml element contents into a DateTime structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000387 value = DateTime()
388 value.decode(data)
389 return value
390
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000391##
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 Montanarobfcbfa72003-04-24 19:51:31 +0000397import base64
398try:
399 import cStringIO as StringIO
400except ImportError:
401 import StringIO
402
Fredrik Lundhb9056332001-07-11 17:42:21 +0000403class Binary:
Fred Drake1b410792001-09-04 18:55:03 +0000404 """Wrapper for binary data."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000405
406 def __init__(self, data=None):
407 self.data = data
408
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000409 ##
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 Lundhb9056332001-07-11 17:42:21 +0000417 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 Lundhb9056332001-07-11 17:42:21 +0000423 self.data = base64.decodestring(data)
424
425 def encode(self, out):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000426 out.write("<value><base64>\n")
427 base64.encode(StringIO.StringIO(self.data), out)
428 out.write("</base64></value>\n")
429
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000430def _binary(data):
431 # decode xml element contents into a Binary structure
Fredrik Lundhb9056332001-07-11 17:42:21 +0000432 value = Binary()
433 value.decode(data)
434 return value
435
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000436WRAPPERS = (DateTime, Binary)
437if not _bool_is_builtin:
438 WRAPPERS = WRAPPERS + (Boolean,)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000439
440# --------------------------------------------------------------------
441# XML parsers
442
443try:
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
449except (AttributeError, ImportError):
450 FastParser = FastUnmarshaller = None
451
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000452try:
453 import _xmlrpclib
454 FastMarshaller = _xmlrpclib.Marshaller
455except (AttributeError, ImportError):
456 FastMarshaller = None
457
Fredrik Lundhb9056332001-07-11 17:42:21 +0000458#
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
465try:
466 import sgmlop
467 if not hasattr(sgmlop, "XMLParser"):
468 raise ImportError
469except ImportError:
470 SgmlopParser = None # sgmlop accelerator not available
471else:
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
508try:
509 from xml.parsers import expat
Guido van Rossumb8551342001-10-02 18:33:11 +0000510 if not hasattr(expat, "ParserCreate"):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000511 raise ImportError
Fredrik Lundhb9056332001-07-11 17:42:21 +0000512except ImportError:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000513 ExpatParser = None # expat not available
Fredrik Lundhb9056332001-07-11 17:42:21 +0000514else:
515 class ExpatParser:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000516 # fast expat parser for Python 2.0 and later. this is about
517 # 50% slower than sgmlop, on roundtrip testing
Fredrik Lundhb9056332001-07-11 17:42:21 +0000518 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 Lundhc4c062f2001-09-10 19:45:02 +0000536class SlowParser:
537 """Default XML parser (based on xmllib.XMLParser)."""
538 # this is about 10 times slower than sgmlop, on roundtrip
539 # testing.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000540 def __init__(self, target):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000541 import xmllib # lazy subclassing (!)
542 if xmllib.XMLParser not in SlowParser.__bases__:
543 SlowParser.__bases__ = (xmllib.XMLParser,)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000544 self.handle_xml = target.xml
545 self.unknown_starttag = target.start
546 self.handle_data = target.data
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000547 self.handle_cdata = target.data
Fredrik Lundhb9056332001-07-11 17:42:21 +0000548 self.unknown_endtag = target.end
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000549 try:
550 xmllib.XMLParser.__init__(self, accept_utf8=1)
551 except TypeError:
552 xmllib.XMLParser.__init__(self) # pre-2.0
Fredrik Lundhb9056332001-07-11 17:42:21 +0000553
554# --------------------------------------------------------------------
555# XML-RPC marshalling and unmarshalling code
556
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000557##
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 Lundhb9056332001-07-11 17:42:21 +0000564class Marshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000565 """Generate an XML-RPC params chunk from a Python data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000566
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000567 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 Drake1b410792001-09-04 18:55:03 +0000572 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000573
574 # by the way, if you don't understand what's going on in here,
575 # that's perfectly ok.
576
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000577 def __init__(self, encoding=None, allow_none=0):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000578 self.memo = {}
579 self.data = None
580 self.encoding = encoding
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000581 self.allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +0000582
Fredrik Lundhb9056332001-07-11 17:42:21 +0000583 dispatch = {}
584
585 def dumps(self, values):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000586 out = []
587 write = out.append
588 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000589 if isinstance(values, Fault):
590 # fault instance
591 write("<fault>\n")
Martin v. Löwis541342f2003-07-12 07:53:04 +0000592 dump({'faultCode': values.faultCode,
593 'faultString': values.faultString},
594 write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000595 write("</fault>\n")
596 else:
597 # parameter block
Fredrik Lundhc266bb02001-08-23 20:13:08 +0000598 # 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 Lundhb9056332001-07-11 17:42:21 +0000603 write("<params>\n")
604 for v in values:
605 write("<param>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000606 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000607 write("</param>\n")
608 write("</params>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000609 result = string.join(out, "")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000610 return result
611
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000612 def __dump(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000613 try:
614 f = self.dispatch[type(value)]
615 except KeyError:
616 raise TypeError, "cannot marshal %s objects" % type(value)
617 else:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000618 f(self, value, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000619
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000620 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 Petersc2659cf2003-05-12 20:19:37 +0000625
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000626 def dump_int(self, value, write):
Skip Montanaro5449e082001-10-17 22:53:33 +0000627 # in case ints are > 32 bits
628 if value > MAXINT or value < MININT:
629 raise OverflowError, "int exceeds XML-RPC limits"
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000630 write("<value><int>")
631 write(str(value))
632 write("</int></value>\n")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000633 dispatch[IntType] = dump_int
634
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000635 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 Lundh3d9addd2002-06-27 21:36:21 +0000642 def dump_long(self, value, write):
Skip Montanaro5449e082001-10-17 22:53:33 +0000643 if value > MAXINT or value < MININT:
644 raise OverflowError, "long int exceeds XML-RPC limits"
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000645 write("<value><int>")
646 write(str(int(value)))
647 write("</int></value>\n")
Skip Montanaro5e9c71b2001-10-10 15:56:34 +0000648 dispatch[LongType] = dump_long
649
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000650 def dump_double(self, value, write):
651 write("<value><double>")
652 write(repr(value))
653 write("</double></value>\n")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000654 dispatch[FloatType] = dump_double
655
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000656 def dump_string(self, value, write, escape=escape):
657 write("<value><string>")
658 write(escape(value))
659 write("</string></value>\n")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000660 dispatch[StringType] = dump_string
661
662 if unicode:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000663 def dump_unicode(self, value, write, escape=escape):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000664 value = value.encode(self.encoding)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000665 write("<value><string>")
666 write(escape(value))
667 write("</string></value>\n")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000668 dispatch[UnicodeType] = dump_unicode
669
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000670 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 Lundh1538c232001-10-01 19:42:03 +0000675 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000676 write("<value><array><data>\n")
677 for v in value:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000678 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000679 write("</data></array></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000680 del self.memo[i]
Fredrik Lundhb9056332001-07-11 17:42:21 +0000681 dispatch[TupleType] = dump_array
682 dispatch[ListType] = dump_array
683
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000684 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 Lundh1538c232001-10-01 19:42:03 +0000689 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000690 write("<value><struct>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000691 for k in value.keys():
Fredrik Lundhb9056332001-07-11 17:42:21 +0000692 write("<member>\n")
693 if type(k) is not StringType:
694 raise TypeError, "dictionary key must be string"
Fredrik Lundh1538c232001-10-01 19:42:03 +0000695 write("<name>%s</name>\n" % escape(k))
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000696 dump(value[k], write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000697 write("</member>\n")
698 write("</struct></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000699 del self.memo[i]
Fredrik Lundhb9056332001-07-11 17:42:21 +0000700 dispatch[DictType] = dump_struct
701
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000702 def dump_instance(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000703 # check for special wrappers
704 if value.__class__ in WRAPPERS:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000705 self.write = write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000706 value.encode(self)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000707 del self.write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000708 else:
709 # store instance attributes as a struct (really?)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000710 self.dump_struct(value.__dict__, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000711 dispatch[InstanceType] = dump_instance
712
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000713##
714# XML-RPC unmarshaller.
715#
716# @see loads
717
Fredrik Lundhb9056332001-07-11 17:42:21 +0000718class Unmarshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000719 """Unmarshal an XML-RPC response, based on incoming XML event
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000720 messages (start, data, end). Call close() to get the resulting
Fred Drake1b410792001-09-04 18:55:03 +0000721 data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000722
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000723 Note that this reader is fairly tolerant, and gladly accepts bogus
724 XML-RPC data without complaining (but not bogus XML).
Fred Drake1b410792001-09-04 18:55:03 +0000725 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000726
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 Rossum68468eb2003-02-27 20:14:51 +0000744 raise Fault(**self._stack[0])
Fredrik Lundhb9056332001-07-11 17:42:21 +0000745 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 Lundh1538c232001-10-01 19:42:03 +0000767 def end(self, tag, join=string.join):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000768 # call the appropriate end tag handler
769 try:
770 f = self.dispatch[tag]
771 except KeyError:
772 pass # unknown tag ?
773 else:
Fredrik Lundh1538c232001-10-01 19:42:03 +0000774 return f(self, join(self._data, ""))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000775
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. Kuchlinga4c2b742003-04-25 00:26:51 +0000793 def end_nil (self, data):
794 self.append(None)
795 self._value = 0
796 dispatch["nil"] = end_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000797
Fredrik Lundh1538c232001-10-01 19:42:03 +0000798 def end_boolean(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000799 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 Lundh1538c232001-10-01 19:42:03 +0000808 def end_int(self, data):
809 self.append(int(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000810 self._value = 0
811 dispatch["i4"] = end_int
812 dispatch["int"] = end_int
813
Fredrik Lundh1538c232001-10-01 19:42:03 +0000814 def end_double(self, data):
815 self.append(float(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000816 self._value = 0
817 dispatch["double"] = end_double
818
Fredrik Lundh1538c232001-10-01 19:42:03 +0000819 def end_string(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000820 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 Hettinger46ac8eb2002-06-30 03:39:14 +0000828 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000829 # 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 Hettinger46ac8eb2002-06-30 03:39:14 +0000835 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000836 # 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 Lundh1538c232001-10-01 19:42:03 +0000845 def end_base64(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000846 value = Binary()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000847 value.decode(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000848 self.append(value)
849 self._value = 0
850 dispatch["base64"] = end_base64
851
Fredrik Lundh1538c232001-10-01 19:42:03 +0000852 def end_dateTime(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000853 value = DateTime()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000854 value.decode(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000855 self.append(value)
856 dispatch["dateTime.iso8601"] = end_dateTime
857
858 def end_value(self, data):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000859 # if we stumble upon a value element with no internal
Fredrik Lundhb9056332001-07-11 17:42:21 +0000860 # 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 Lundh1538c232001-10-01 19:42:03 +0000873 def end_methodName(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000874 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öwis45394c22003-10-31 13:49:36 +0000880## Multicall support
881#
Fredrik Lundhb9056332001-07-11 17:42:21 +0000882
Martin v. Löwis45394c22003-10-31 13:49:36 +0000883class _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
894def MultiCallIterator(results):
895 """Iterates over the results of a multicall. Exceptions are
896 thrown in response to xmlrpc faults."""
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000897
Martin v. Löwis45394c22003-10-31 13:49:36 +0000898 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 Hettingercc523fc2003-11-02 09:47:05 +0000906
Martin v. Löwis45394c22003-10-31 13:49:36 +0000907class 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 Hettingercc523fc2003-11-02 09:47:05 +0000923
Martin v. Löwis45394c22003-10-31 13:49:36 +0000924 def __init__(self, server):
925 self.__server = server
926 self.__call_list = []
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000927
Martin v. Löwis45394c22003-10-31 13:49:36 +0000928 def __repr__(self):
929 return "<MultiCall at %x>" % id(self)
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000930
Martin v. Löwis45394c22003-10-31 13:49:36 +0000931 __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 Hettingercc523fc2003-11-02 09:47:05 +0000942
Fredrik Lundhb9056332001-07-11 17:42:21 +0000943# --------------------------------------------------------------------
944# convenience functions
945
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000946##
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 Lundhb9056332001-07-11 17:42:21 +0000952def getparser():
953 """getparser() -> parser, unmarshaller
954
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000955 Create an instance of the fastest available parser, and attach it
956 to an unmarshalling object. Return both objects.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000957 """
958 if FastParser and FastUnmarshaller:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000959 target = FastUnmarshaller(True, False, _binary, _datetime, Fault)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000960 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 Lundh3d9addd2002-06-27 21:36:21 +0000973##
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. Kuchlinga4c2b742003-04-25 00:26:51 +0000986def dumps(params, methodname=None, methodresponse=None, encoding=None,
987 allow_none=0):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000988 """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 Lundhb0e8e9b2001-09-10 21:45:42 +0000993 In addition to the data object, the following options can be given
994 as keyword arguments:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000995
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 Lundhb0e8e9b2001-09-10 21:45:42 +00001006 where necessary.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001007 """
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 Lundh3d9addd2002-06-27 21:36:21 +00001017 if not encoding:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001018 encoding = "utf-8"
1019
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001020 if FastMarshaller:
1021 m = FastMarshaller(encoding)
1022 else:
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001023 m = Marshaller(encoding, allow_none)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001024
Fredrik Lundhb9056332001-07-11 17:42:21 +00001025 data = m.dumps(params)
1026
1027 if encoding != "utf-8":
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001028 xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001029 else:
1030 xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
1031
1032 # standard XML-RPC wrappings
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001033 if methodname:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001034 # 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 Lundh3d9addd2002-06-27 21:36:21 +00001056##
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örwaldf0dfc7a2003-10-20 14:01:56 +00001061# @return A tuple containing the unpacked data, and the method name
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001062# (None if not present).
1063# @see Fault
1064
Fredrik Lundhb9056332001-07-11 17:42:21 +00001065def 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
1083class _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 Lundh3d9addd2002-06-27 21:36:21 +00001094##
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 Lundhb9056332001-07-11 17:42:21 +00001099
1100class Transport:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001101 """Handles an HTTP transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001102
1103 # client identifier (may be overridden)
1104 user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
1105
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001106 ##
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 Lundhb9056332001-07-11 17:42:21 +00001115 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 Lundh3d9addd2002-06-27 21:36:21 +00001138 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 Lundhb9056332001-07-11 17:42:21 +00001149
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001150 def getparser(self):
1151 # get parser and unmarshaller
1152 return getparser()
1153
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001154 ##
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001155 # 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 Lundh768c98b2002-11-01 17:14:16 +00001175 auth = base64.encodestring(urllib.unquote(auth))
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001176 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 Lundh3d9addd2002-06-27 21:36:21 +00001186 # Connect to server.
1187 #
1188 # @param host Target host.
1189 # @return A connection handle.
1190
Fredrik Lundhb9056332001-07-11 17:42:21 +00001191 def make_connection(self, host):
1192 # create a HTTP connection object from a host descriptor
1193 import httplib
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001194 host, extra_headers, x509 = self.get_host_info(host)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001195 return httplib.HTTP(host)
1196
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001197 ##
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 Lundhb9056332001-07-11 17:42:21 +00001204 def send_request(self, connection, handler, request_body):
1205 connection.putrequest("POST", handler)
1206
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001207 ##
1208 # Send host name.
1209 #
1210 # @param connection Connection handle.
1211 # @param host Host name.
1212
Fredrik Lundhb9056332001-07-11 17:42:21 +00001213 def send_host(self, connection, host):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001214 host, extra_headers, x509 = self.get_host_info(host)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001215 connection.putheader("Host", host)
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001216 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 Lundhb9056332001-07-11 17:42:21 +00001221
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001222 ##
1223 # Send user-agent identifier.
1224 #
1225 # @param connection Connection handle.
1226
Fredrik Lundhb9056332001-07-11 17:42:21 +00001227 def send_user_agent(self, connection):
1228 connection.putheader("User-Agent", self.user_agent)
1229
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001230 ##
1231 # Send request body.
1232 #
1233 # @param connection Connection handle.
1234 # @param request_body XML-RPC request body.
1235
Fredrik Lundhb9056332001-07-11 17:42:21 +00001236 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 Lundh3d9addd2002-06-27 21:36:21 +00001243 ##
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 Lundhb9056332001-07-11 17:42:21 +00001265
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001266 p, u = self.getparser()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001267
1268 while 1:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001269 if sock:
1270 response = sock.recv(1024)
1271 else:
1272 response = file.read(1024)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001273 if not response:
1274 break
1275 if self.verbose:
1276 print "body:", repr(response)
1277 p.feed(response)
1278
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001279 file.close()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001280 p.close()
1281
1282 return u.close()
1283
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001284##
1285# Standard transport class for XML-RPC over HTTPS.
1286
Fredrik Lundhb9056332001-07-11 17:42:21 +00001287class SafeTransport(Transport):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001288 """Handles an HTTPS transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001289
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001290 # FIXME: mostly untested
1291
Fredrik Lundhb9056332001-07-11 17:42:21 +00001292 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 Lundh1303c7c2002-10-22 18:23:00 +00001296 host, extra_headers, x509 = self.get_host_info(host)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001297 try:
1298 HTTPS = httplib.HTTPS
1299 except AttributeError:
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001300 raise NotImplementedError(
1301 "your version of httplib doesn't support HTTPS"
1302 )
Fredrik Lundhb9056332001-07-11 17:42:21 +00001303 else:
Guido van Rossum68468eb2003-02-27 20:14:51 +00001304 return HTTPS(host, None, **(x509 or {}))
Fredrik Lundhb9056332001-07-11 17:42:21 +00001305
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001306##
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 Lundhb9056332001-07-11 17:42:21 +00001323class 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. Kuchlinga4c2b742003-04-25 00:26:51 +00001345 def __init__(self, uri, transport=None, encoding=None, verbose=0,
1346 allow_none=0):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001347 # establish a "logical" server connection
1348
1349 # get the url
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001350 import urllib
Fredrik Lundhb9056332001-07-11 17:42:21 +00001351 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. Kuchlinga4c2b742003-04-25 00:26:51 +00001367 self.__allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +00001368
Fredrik Lundhb9056332001-07-11 17:42:21 +00001369 def __request(self, methodname, params):
1370 # call a method on the remote server
1371
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001372 request = dumps(params, methodname, encoding=self.__encoding,
1373 allow_none=self.__allow_none)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001374
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 Lundh78eedce2001-08-23 20:04:33 +00001389 "<ServerProxy for %s%s>" %
Fredrik Lundhb9056332001-07-11 17:42:21 +00001390 (self.__host, self.__handler)
1391 )
1392
1393 __str__ = __repr__
Raymond Hettingercc523fc2003-11-02 09:47:05 +00001394
Fredrik Lundhb9056332001-07-11 17:42:21 +00001395 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 Lundh78eedce2001-08-23 20:04:33 +00001402# compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001403
Fredrik Lundhb9056332001-07-11 17:42:21 +00001404Server = ServerProxy
1405
1406# --------------------------------------------------------------------
1407# test code
1408
1409if __name__ == "__main__":
1410
1411 # simple test program (from the XML-RPC specification)
1412
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001413 # server = ServerProxy("http://localhost:8000") # local server
Tim Petersc2659cf2003-05-12 20:19:37 +00001414 server = ServerProxy("http://betty.userland.com")
Fredrik Lundhb9056332001-07-11 17:42:21 +00001415
1416 print server
1417
1418 try:
1419 print server.examples.getStateName(41)
1420 except Error, v:
1421 print "ERROR", v