blob: e7eb4664947949174afd6a0d2007eefe0519149e [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")
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000691 for k, v in value.items():
Fredrik Lundhb9056332001-07-11 17:42:21 +0000692 write("<member>\n")
693 if type(k) is not StringType:
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000694 if unicode and type(k) is UnicodeType:
695 k = k.encode(self.encoding)
696 else:
697 raise TypeError, "dictionary key must be string"
Fredrik Lundh1538c232001-10-01 19:42:03 +0000698 write("<name>%s</name>\n" % escape(k))
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000699 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000700 write("</member>\n")
701 write("</struct></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000702 del self.memo[i]
Fredrik Lundhb9056332001-07-11 17:42:21 +0000703 dispatch[DictType] = dump_struct
704
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000705 def dump_instance(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000706 # check for special wrappers
707 if value.__class__ in WRAPPERS:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000708 self.write = write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000709 value.encode(self)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000710 del self.write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000711 else:
712 # store instance attributes as a struct (really?)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000713 self.dump_struct(value.__dict__, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000714 dispatch[InstanceType] = dump_instance
715
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000716##
717# XML-RPC unmarshaller.
718#
719# @see loads
720
Fredrik Lundhb9056332001-07-11 17:42:21 +0000721class Unmarshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000722 """Unmarshal an XML-RPC response, based on incoming XML event
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000723 messages (start, data, end). Call close() to get the resulting
Fred Drake1b410792001-09-04 18:55:03 +0000724 data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000725
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000726 Note that this reader is fairly tolerant, and gladly accepts bogus
727 XML-RPC data without complaining (but not bogus XML).
Fred Drake1b410792001-09-04 18:55:03 +0000728 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000729
730 # and again, if you don't understand what's going on in here,
731 # that's perfectly ok.
732
733 def __init__(self):
734 self._type = None
735 self._stack = []
736 self._marks = []
737 self._data = []
738 self._methodname = None
739 self._encoding = "utf-8"
740 self.append = self._stack.append
741
742 def close(self):
743 # return response tuple and target method
744 if self._type is None or self._marks:
745 raise ResponseError()
746 if self._type == "fault":
Guido van Rossum68468eb2003-02-27 20:14:51 +0000747 raise Fault(**self._stack[0])
Fredrik Lundhb9056332001-07-11 17:42:21 +0000748 return tuple(self._stack)
749
750 def getmethodname(self):
751 return self._methodname
752
753 #
754 # event handlers
755
756 def xml(self, encoding, standalone):
757 self._encoding = encoding
758 # FIXME: assert standalone == 1 ???
759
760 def start(self, tag, attrs):
761 # prepare to handle this element
762 if tag == "array" or tag == "struct":
763 self._marks.append(len(self._stack))
764 self._data = []
765 self._value = (tag == "value")
766
767 def data(self, text):
768 self._data.append(text)
769
Fredrik Lundh1538c232001-10-01 19:42:03 +0000770 def end(self, tag, join=string.join):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000771 # call the appropriate end tag handler
772 try:
773 f = self.dispatch[tag]
774 except KeyError:
775 pass # unknown tag ?
776 else:
Fredrik Lundh1538c232001-10-01 19:42:03 +0000777 return f(self, join(self._data, ""))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000778
779 #
780 # accelerator support
781
782 def end_dispatch(self, tag, data):
783 # dispatch data
784 try:
785 f = self.dispatch[tag]
786 except KeyError:
787 pass # unknown tag ?
788 else:
789 return f(self, data)
790
791 #
792 # element decoders
793
794 dispatch = {}
795
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000796 def end_nil (self, data):
797 self.append(None)
798 self._value = 0
799 dispatch["nil"] = end_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000800
Fredrik Lundh1538c232001-10-01 19:42:03 +0000801 def end_boolean(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000802 if data == "0":
803 self.append(False)
804 elif data == "1":
805 self.append(True)
806 else:
807 raise TypeError, "bad boolean value"
808 self._value = 0
809 dispatch["boolean"] = end_boolean
810
Fredrik Lundh1538c232001-10-01 19:42:03 +0000811 def end_int(self, data):
812 self.append(int(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000813 self._value = 0
814 dispatch["i4"] = end_int
815 dispatch["int"] = end_int
816
Fredrik Lundh1538c232001-10-01 19:42:03 +0000817 def end_double(self, data):
818 self.append(float(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000819 self._value = 0
820 dispatch["double"] = end_double
821
Fredrik Lundh1538c232001-10-01 19:42:03 +0000822 def end_string(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000823 if self._encoding:
824 data = _decode(data, self._encoding)
825 self.append(_stringify(data))
826 self._value = 0
827 dispatch["string"] = end_string
828 dispatch["name"] = end_string # struct keys are always strings
829
830 def end_array(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000831 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000832 # map arrays to Python lists
833 self._stack[mark:] = [self._stack[mark:]]
834 self._value = 0
835 dispatch["array"] = end_array
836
837 def end_struct(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000838 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000839 # map structs to Python dictionaries
840 dict = {}
841 items = self._stack[mark:]
842 for i in range(0, len(items), 2):
843 dict[_stringify(items[i])] = items[i+1]
844 self._stack[mark:] = [dict]
845 self._value = 0
846 dispatch["struct"] = end_struct
847
Fredrik Lundh1538c232001-10-01 19:42:03 +0000848 def end_base64(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000849 value = Binary()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000850 value.decode(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000851 self.append(value)
852 self._value = 0
853 dispatch["base64"] = end_base64
854
Fredrik Lundh1538c232001-10-01 19:42:03 +0000855 def end_dateTime(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000856 value = DateTime()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000857 value.decode(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000858 self.append(value)
859 dispatch["dateTime.iso8601"] = end_dateTime
860
861 def end_value(self, data):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000862 # if we stumble upon a value element with no internal
Fredrik Lundhb9056332001-07-11 17:42:21 +0000863 # elements, treat it as a string element
864 if self._value:
865 self.end_string(data)
866 dispatch["value"] = end_value
867
868 def end_params(self, data):
869 self._type = "params"
870 dispatch["params"] = end_params
871
872 def end_fault(self, data):
873 self._type = "fault"
874 dispatch["fault"] = end_fault
875
Fredrik Lundh1538c232001-10-01 19:42:03 +0000876 def end_methodName(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000877 if self._encoding:
878 data = _decode(data, self._encoding)
879 self._methodname = data
880 self._type = "methodName" # no params
881 dispatch["methodName"] = end_methodName
882
Martin v. Löwis45394c22003-10-31 13:49:36 +0000883## Multicall support
884#
Fredrik Lundhb9056332001-07-11 17:42:21 +0000885
Martin v. Löwis45394c22003-10-31 13:49:36 +0000886class _MultiCallMethod:
887 # some lesser magic to store calls made to a MultiCall object
888 # for batch execution
889 def __init__(self, call_list, name):
890 self.__call_list = call_list
891 self.__name = name
892 def __getattr__(self, name):
893 return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
894 def __call__(self, *args):
895 self.__call_list.append((self.__name, args))
896
897def MultiCallIterator(results):
898 """Iterates over the results of a multicall. Exceptions are
899 thrown in response to xmlrpc faults."""
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000900
Martin v. Löwis45394c22003-10-31 13:49:36 +0000901 for i in results:
902 if type(i) == type({}):
903 raise Fault(i['faultCode'], i['faultString'])
904 elif type(i) == type([]):
905 yield i[0]
906 else:
907 raise ValueError,\
908 "unexpected type in multicall result"
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000909
Martin v. Löwis45394c22003-10-31 13:49:36 +0000910class MultiCall:
911 """server -> a object used to boxcar method calls
912
913 server should be a ServerProxy object.
914
915 Methods can be added to the MultiCall using normal
916 method call syntax e.g.:
917
918 multicall = MultiCall(server_proxy)
919 multicall.add(2,3)
920 multicall.get_address("Guido")
921
922 To execute the multicall, call the MultiCall object e.g.:
923
924 add_result, address = multicall()
925 """
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000926
Martin v. Löwis45394c22003-10-31 13:49:36 +0000927 def __init__(self, server):
928 self.__server = server
929 self.__call_list = []
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000930
Martin v. Löwis45394c22003-10-31 13:49:36 +0000931 def __repr__(self):
932 return "<MultiCall at %x>" % id(self)
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000933
Martin v. Löwis45394c22003-10-31 13:49:36 +0000934 __str__ = __repr__
935
936 def __getattr__(self, name):
937 return _MultiCallMethod(self.__call_list, name)
938
939 def __call__(self):
940 marshalled_list = []
941 for name, args in self.__call_list:
942 marshalled_list.append({'methodName' : name, 'params' : args})
943
944 return MultiCallIterator(self.__server.system.multicall(marshalled_list))
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000945
Fredrik Lundhb9056332001-07-11 17:42:21 +0000946# --------------------------------------------------------------------
947# convenience functions
948
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000949##
950# Create a parser object, and connect it to an unmarshalling instance.
951# This function picks the fastest available XML parser.
952#
953# return A (parser, unmarshaller) tuple.
954
Fredrik Lundhb9056332001-07-11 17:42:21 +0000955def getparser():
956 """getparser() -> parser, unmarshaller
957
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000958 Create an instance of the fastest available parser, and attach it
959 to an unmarshalling object. Return both objects.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000960 """
961 if FastParser and FastUnmarshaller:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000962 target = FastUnmarshaller(True, False, _binary, _datetime, Fault)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000963 parser = FastParser(target)
964 else:
965 target = Unmarshaller()
966 if FastParser:
967 parser = FastParser(target)
968 elif SgmlopParser:
969 parser = SgmlopParser(target)
970 elif ExpatParser:
971 parser = ExpatParser(target)
972 else:
973 parser = SlowParser(target)
974 return parser, target
975
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000976##
977# Convert a Python tuple or a Fault instance to an XML-RPC packet.
978#
979# @def dumps(params, **options)
980# @param params A tuple or Fault instance.
981# @keyparam methodname If given, create a methodCall request for
982# this method name.
983# @keyparam methodresponse If given, create a methodResponse packet.
984# If used with a tuple, the tuple must be a singleton (that is,
985# it must contain exactly one element).
986# @keyparam encoding The packet encoding.
987# @return A string containing marshalled data.
988
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000989def dumps(params, methodname=None, methodresponse=None, encoding=None,
990 allow_none=0):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000991 """data [,options] -> marshalled data
992
993 Convert an argument tuple or a Fault instance to an XML-RPC
994 request (or response, if the methodresponse option is used).
995
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000996 In addition to the data object, the following options can be given
997 as keyword arguments:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000998
999 methodname: the method name for a methodCall packet
1000
1001 methodresponse: true to create a methodResponse packet.
1002 If this option is used with a tuple, the tuple must be
1003 a singleton (i.e. it can contain only one element).
1004
1005 encoding: the packet encoding (default is UTF-8)
1006
1007 All 8-bit strings in the data structure are assumed to use the
1008 packet encoding. Unicode strings are automatically converted,
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +00001009 where necessary.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001010 """
1011
1012 assert isinstance(params, TupleType) or isinstance(params, Fault),\
1013 "argument must be tuple or Fault instance"
1014
1015 if isinstance(params, Fault):
1016 methodresponse = 1
1017 elif methodresponse and isinstance(params, TupleType):
1018 assert len(params) == 1, "response tuple must be a singleton"
1019
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001020 if not encoding:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001021 encoding = "utf-8"
1022
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001023 if FastMarshaller:
1024 m = FastMarshaller(encoding)
1025 else:
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001026 m = Marshaller(encoding, allow_none)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001027
Fredrik Lundhb9056332001-07-11 17:42:21 +00001028 data = m.dumps(params)
1029
1030 if encoding != "utf-8":
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001031 xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001032 else:
1033 xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
1034
1035 # standard XML-RPC wrappings
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001036 if methodname:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001037 # a method call
1038 if not isinstance(methodname, StringType):
1039 methodname = methodname.encode(encoding)
1040 data = (
1041 xmlheader,
1042 "<methodCall>\n"
1043 "<methodName>", methodname, "</methodName>\n",
1044 data,
1045 "</methodCall>\n"
1046 )
1047 elif methodresponse:
1048 # a method response, or a fault structure
1049 data = (
1050 xmlheader,
1051 "<methodResponse>\n",
1052 data,
1053 "</methodResponse>\n"
1054 )
1055 else:
1056 return data # return as is
1057 return string.join(data, "")
1058
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001059##
1060# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
1061# represents a fault condition, this function raises a Fault exception.
1062#
1063# @param data An XML-RPC packet, given as an 8-bit string.
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00001064# @return A tuple containing the unpacked data, and the method name
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001065# (None if not present).
1066# @see Fault
1067
Fredrik Lundhb9056332001-07-11 17:42:21 +00001068def loads(data):
1069 """data -> unmarshalled data, method name
1070
1071 Convert an XML-RPC packet to unmarshalled data plus a method
1072 name (None if not present).
1073
1074 If the XML-RPC packet represents a fault condition, this function
1075 raises a Fault exception.
1076 """
1077 p, u = getparser()
1078 p.feed(data)
1079 p.close()
1080 return u.close(), u.getmethodname()
1081
1082
1083# --------------------------------------------------------------------
1084# request dispatcher
1085
1086class _Method:
1087 # some magic to bind an XML-RPC method to an RPC server.
1088 # supports "nested" methods (e.g. examples.getStateName)
1089 def __init__(self, send, name):
1090 self.__send = send
1091 self.__name = name
1092 def __getattr__(self, name):
1093 return _Method(self.__send, "%s.%s" % (self.__name, name))
1094 def __call__(self, *args):
1095 return self.__send(self.__name, args)
1096
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001097##
1098# Standard transport class for XML-RPC over HTTP.
1099# <p>
1100# You can create custom transports by subclassing this method, and
1101# overriding selected methods.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001102
1103class Transport:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001104 """Handles an HTTP transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001105
1106 # client identifier (may be overridden)
1107 user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
1108
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001109 ##
1110 # Send a complete request, and parse the response.
1111 #
1112 # @param host Target host.
1113 # @param handler Target PRC handler.
1114 # @param request_body XML-RPC request body.
1115 # @param verbose Debugging flag.
1116 # @return Parsed response.
1117
Fredrik Lundhb9056332001-07-11 17:42:21 +00001118 def request(self, host, handler, request_body, verbose=0):
1119 # issue XML-RPC request
1120
1121 h = self.make_connection(host)
1122 if verbose:
1123 h.set_debuglevel(1)
1124
1125 self.send_request(h, handler, request_body)
1126 self.send_host(h, host)
1127 self.send_user_agent(h)
1128 self.send_content(h, request_body)
1129
1130 errcode, errmsg, headers = h.getreply()
1131
1132 if errcode != 200:
1133 raise ProtocolError(
1134 host + handler,
1135 errcode, errmsg,
1136 headers
1137 )
1138
1139 self.verbose = verbose
1140
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001141 try:
1142 sock = h._conn.sock
1143 except AttributeError:
1144 sock = None
1145
1146 return self._parse_response(h.getfile(), sock)
1147
1148 ##
1149 # Create parser.
1150 #
1151 # @return A 2-tuple containing a parser and a unmarshaller.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001152
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001153 def getparser(self):
1154 # get parser and unmarshaller
1155 return getparser()
1156
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001157 ##
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001158 # Get authorization info from host parameter
1159 # Host may be a string, or a (host, x509-dict) tuple; if a string,
1160 # it is checked for a "user:pw@host" format, and a "Basic
1161 # Authentication" header is added if appropriate.
1162 #
1163 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1164 # @return A 3-tuple containing (actual host, extra headers,
1165 # x509 info). The header and x509 fields may be None.
1166
1167 def get_host_info(self, host):
1168
1169 x509 = {}
1170 if isinstance(host, TupleType):
1171 host, x509 = host
1172
1173 import urllib
1174 auth, host = urllib.splituser(host)
1175
1176 if auth:
1177 import base64
Fredrik Lundh768c98b2002-11-01 17:14:16 +00001178 auth = base64.encodestring(urllib.unquote(auth))
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001179 auth = string.join(string.split(auth), "") # get rid of whitespace
1180 extra_headers = [
1181 ("Authorization", "Basic " + auth)
1182 ]
1183 else:
1184 extra_headers = None
1185
1186 return host, extra_headers, x509
1187
1188 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001189 # Connect to server.
1190 #
1191 # @param host Target host.
1192 # @return A connection handle.
1193
Fredrik Lundhb9056332001-07-11 17:42:21 +00001194 def make_connection(self, host):
1195 # create a HTTP connection object from a host descriptor
1196 import httplib
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001197 host, extra_headers, x509 = self.get_host_info(host)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001198 return httplib.HTTP(host)
1199
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001200 ##
1201 # Send request header.
1202 #
1203 # @param connection Connection handle.
1204 # @param handler Target RPC handler.
1205 # @param request_body XML-RPC body.
1206
Fredrik Lundhb9056332001-07-11 17:42:21 +00001207 def send_request(self, connection, handler, request_body):
1208 connection.putrequest("POST", handler)
1209
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001210 ##
1211 # Send host name.
1212 #
1213 # @param connection Connection handle.
1214 # @param host Host name.
1215
Fredrik Lundhb9056332001-07-11 17:42:21 +00001216 def send_host(self, connection, host):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001217 host, extra_headers, x509 = self.get_host_info(host)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001218 connection.putheader("Host", host)
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001219 if extra_headers:
1220 if isinstance(extra_headers, DictType):
1221 extra_headers = extra_headers.items()
1222 for key, value in extra_headers:
1223 connection.putheader(key, value)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001224
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001225 ##
1226 # Send user-agent identifier.
1227 #
1228 # @param connection Connection handle.
1229
Fredrik Lundhb9056332001-07-11 17:42:21 +00001230 def send_user_agent(self, connection):
1231 connection.putheader("User-Agent", self.user_agent)
1232
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001233 ##
1234 # Send request body.
1235 #
1236 # @param connection Connection handle.
1237 # @param request_body XML-RPC request body.
1238
Fredrik Lundhb9056332001-07-11 17:42:21 +00001239 def send_content(self, connection, request_body):
1240 connection.putheader("Content-Type", "text/xml")
1241 connection.putheader("Content-Length", str(len(request_body)))
1242 connection.endheaders()
1243 if request_body:
1244 connection.send(request_body)
1245
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001246 ##
1247 # Parse response.
1248 #
1249 # @param file Stream.
1250 # @return Response tuple and target method.
1251
1252 def parse_response(self, file):
1253 # compatibility interface
1254 return self._parse_response(file, None)
1255
1256 ##
1257 # Parse response (alternate interface). This is similar to the
1258 # parse_response method, but also provides direct access to the
1259 # underlying socket object (where available).
1260 #
1261 # @param file Stream.
1262 # @param sock Socket handle (or None, if the socket object
1263 # could not be accessed).
1264 # @return Response tuple and target method.
1265
1266 def _parse_response(self, file, sock):
1267 # read response from input file/socket, and parse it
Fredrik Lundhb9056332001-07-11 17:42:21 +00001268
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001269 p, u = self.getparser()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001270
1271 while 1:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001272 if sock:
1273 response = sock.recv(1024)
1274 else:
1275 response = file.read(1024)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001276 if not response:
1277 break
1278 if self.verbose:
1279 print "body:", repr(response)
1280 p.feed(response)
1281
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001282 file.close()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001283 p.close()
1284
1285 return u.close()
1286
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001287##
1288# Standard transport class for XML-RPC over HTTPS.
1289
Fredrik Lundhb9056332001-07-11 17:42:21 +00001290class SafeTransport(Transport):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001291 """Handles an HTTPS transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001292
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001293 # FIXME: mostly untested
1294
Fredrik Lundhb9056332001-07-11 17:42:21 +00001295 def make_connection(self, host):
1296 # create a HTTPS connection object from a host descriptor
1297 # host may be a string, or a (host, x509-dict) tuple
1298 import httplib
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001299 host, extra_headers, x509 = self.get_host_info(host)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001300 try:
1301 HTTPS = httplib.HTTPS
1302 except AttributeError:
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001303 raise NotImplementedError(
1304 "your version of httplib doesn't support HTTPS"
1305 )
Fredrik Lundhb9056332001-07-11 17:42:21 +00001306 else:
Guido van Rossum68468eb2003-02-27 20:14:51 +00001307 return HTTPS(host, None, **(x509 or {}))
Fredrik Lundhb9056332001-07-11 17:42:21 +00001308
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001309##
1310# Standard server proxy. This class establishes a virtual connection
1311# to an XML-RPC server.
1312# <p>
1313# This class is available as ServerProxy and Server. New code should
1314# use ServerProxy, to avoid confusion.
1315#
1316# @def ServerProxy(uri, **options)
1317# @param uri The connection point on the server.
1318# @keyparam transport A transport factory, compatible with the
1319# standard transport class.
1320# @keyparam encoding The default encoding used for 8-bit strings
1321# (default is UTF-8).
1322# @keyparam verbose Use a true value to enable debugging output.
1323# (printed to standard output).
1324# @see Transport
1325
Fredrik Lundhb9056332001-07-11 17:42:21 +00001326class ServerProxy:
1327 """uri [,options] -> a logical connection to an XML-RPC server
1328
1329 uri is the connection point on the server, given as
1330 scheme://host/target.
1331
1332 The standard implementation always supports the "http" scheme. If
1333 SSL socket support is available (Python 2.0), it also supports
1334 "https".
1335
1336 If the target part and the slash preceding it are both omitted,
1337 "/RPC2" is assumed.
1338
1339 The following options can be given as keyword arguments:
1340
1341 transport: a transport factory
1342 encoding: the request encoding (default is UTF-8)
1343
1344 All 8-bit strings passed to the server proxy are assumed to use
1345 the given encoding.
1346 """
1347
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001348 def __init__(self, uri, transport=None, encoding=None, verbose=0,
1349 allow_none=0):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001350 # establish a "logical" server connection
1351
1352 # get the url
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001353 import urllib
Fredrik Lundhb9056332001-07-11 17:42:21 +00001354 type, uri = urllib.splittype(uri)
1355 if type not in ("http", "https"):
1356 raise IOError, "unsupported XML-RPC protocol"
1357 self.__host, self.__handler = urllib.splithost(uri)
1358 if not self.__handler:
1359 self.__handler = "/RPC2"
1360
1361 if transport is None:
1362 if type == "https":
1363 transport = SafeTransport()
1364 else:
1365 transport = Transport()
1366 self.__transport = transport
1367
1368 self.__encoding = encoding
1369 self.__verbose = verbose
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001370 self.__allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +00001371
Fredrik Lundhb9056332001-07-11 17:42:21 +00001372 def __request(self, methodname, params):
1373 # call a method on the remote server
1374
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001375 request = dumps(params, methodname, encoding=self.__encoding,
1376 allow_none=self.__allow_none)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001377
1378 response = self.__transport.request(
1379 self.__host,
1380 self.__handler,
1381 request,
1382 verbose=self.__verbose
1383 )
1384
1385 if len(response) == 1:
1386 response = response[0]
1387
1388 return response
1389
1390 def __repr__(self):
1391 return (
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001392 "<ServerProxy for %s%s>" %
Fredrik Lundhb9056332001-07-11 17:42:21 +00001393 (self.__host, self.__handler)
1394 )
1395
1396 __str__ = __repr__
Raymond Hettingercc523fc2003-11-02 09:47:05 +00001397
Fredrik Lundhb9056332001-07-11 17:42:21 +00001398 def __getattr__(self, name):
1399 # magic method dispatcher
1400 return _Method(self.__request, name)
1401
1402 # note: to call a remote object with an non-standard name, use
1403 # result getattr(server, "strange-python-name")(args)
1404
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001405# compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001406
Fredrik Lundhb9056332001-07-11 17:42:21 +00001407Server = ServerProxy
1408
1409# --------------------------------------------------------------------
1410# test code
1411
1412if __name__ == "__main__":
1413
1414 # simple test program (from the XML-RPC specification)
1415
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001416 # server = ServerProxy("http://localhost:8000") # local server
Tim Petersc2659cf2003-05-12 20:19:37 +00001417 server = ServerProxy("http://betty.userland.com")
Fredrik Lundhb9056332001-07-11 17:42:21 +00001418
1419 print server
1420
1421 try:
1422 print server.examples.getStateName(41)
1423 except Error, v:
1424 print "ERROR", v