blob: 3cd000af723d94c68a07ad4718035d49c7c6541d [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:
Martin v. Löwis37af9862004-08-20 07:31:37 +000011# this version is designed to work with Python 2.1 or newer.
Fredrik Lundhc4c062f2001-09-10 19:45:02 +000012#
Fredrik Lundhb9056332001-07-11 17:42:21 +000013# History:
14# 1999-01-14 fl Created
15# 1999-01-15 fl Changed dateTime to use localtime
16# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
17# 1999-01-19 fl Fixed array data element (from Skip Montanaro)
18# 1999-01-21 fl Fixed dateTime constructor, etc.
19# 1999-02-02 fl Added fault handling, handle empty sequences, etc.
20# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
21# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
22# 2000-11-28 fl Changed boolean to check the truth value of its argument
23# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
24# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
25# 2001-03-28 fl Make sure response tuple is a singleton
26# 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
Fredrik Lundh78eedce2001-08-23 20:04:33 +000027# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
28# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
Fredrik Lundhc4c062f2001-09-10 19:45:02 +000029# 2001-09-03 fl Allow Transport subclass to override getparser
30# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
Fredrik Lundh1538c232001-10-01 19:42:03 +000031# 2001-10-01 fl Remove containers from memo cache when done with them
32# 2001-10-01 fl Use faster escape method (80% dumps speedup)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000033# 2001-10-02 fl More dumps microtuning
34# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
Skip Montanaro5e9c71b2001-10-10 15:56:34 +000035# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000036# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
Fredrik Lundhb6ab93f2001-12-19 21:40:04 +000037# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000038# 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
39# 2002-04-07 fl Added pythondoc comments
40# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
41# 2002-05-15 fl Added error constants (from Andrew Kuchling)
42# 2002-06-27 fl Merged with Python CVS version
Fredrik Lundh1303c7c2002-10-22 18:23:00 +000043# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
Martin v. Löwis541342f2003-07-12 07:53:04 +000044# 2003-01-22 sm Add support for the bool type
45# 2003-02-27 gvr Remove apply calls
46# 2003-04-24 sm Use cStringIO if available
47# 2003-04-25 ak Add support for nil
48# 2003-06-15 gn Add support for time.struct_time
49# 2003-07-12 gp Correct marshalling of Faults
Martin v. Löwis45394c22003-10-31 13:49:36 +000050# 2003-10-31 mvl Add multicall support
Martin v. Löwis37af9862004-08-20 07:31:37 +000051# 2004-08-20 mvl Bump minimum supported Python version to 2.1
Fredrik Lundhb9056332001-07-11 17:42:21 +000052#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000053# Copyright (c) 1999-2002 by Secret Labs AB.
54# Copyright (c) 1999-2002 by Fredrik Lundh.
Fredrik Lundhb9056332001-07-11 17:42:21 +000055#
56# info@pythonware.com
57# http://www.pythonware.com
58#
59# --------------------------------------------------------------------
60# The XML-RPC client interface is
61#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000062# Copyright (c) 1999-2002 by Secret Labs AB
63# Copyright (c) 1999-2002 by Fredrik Lundh
Fredrik Lundhb9056332001-07-11 17:42:21 +000064#
65# By obtaining, using, and/or copying this software and/or its
66# associated documentation, you agree that you have read, understood,
67# and will comply with the following terms and conditions:
68#
69# Permission to use, copy, modify, and distribute this software and
70# its associated documentation for any purpose and without fee is
71# hereby granted, provided that the above copyright notice appears in
72# all copies, and that both that copyright notice and this permission
73# notice appear in supporting documentation, and that the name of
74# Secret Labs AB or the author not be used in advertising or publicity
75# pertaining to distribution of the software without specific, written
76# prior permission.
77#
78# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
79# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
80# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
81# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
82# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
83# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
84# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
85# OF THIS SOFTWARE.
86# --------------------------------------------------------------------
87
88#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000089# things to look into some day:
Fredrik Lundhb9056332001-07-11 17:42:21 +000090
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000091# TODO: sort out True/False/boolean issues for Python 2.3
Fredrik Lundhb9056332001-07-11 17:42:21 +000092
Fred Drake1b410792001-09-04 18:55:03 +000093"""
94An XML-RPC client interface for Python.
95
96The marshalling and response parser code can also be used to
97implement XML-RPC servers.
98
Fred Drake1b410792001-09-04 18:55:03 +000099Exported exceptions:
100
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000101 Error Base class for client errors
102 ProtocolError Indicates an HTTP protocol error
103 ResponseError Indicates a broken response package
104 Fault Indicates an XML-RPC fault package
Fred Drake1b410792001-09-04 18:55:03 +0000105
106Exported classes:
107
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000108 ServerProxy Represents a logical connection to an XML-RPC server
Fred Drake1b410792001-09-04 18:55:03 +0000109
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000110 MultiCall Executor of boxcared xmlrpc requests
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000111 DateTime dateTime wrapper for an ISO 8601 string or time tuple or
112 localtime integer value to generate a "dateTime.iso8601"
113 XML-RPC value
114 Binary binary data wrapper
Fred Drake1b410792001-09-04 18:55:03 +0000115
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000116 Marshaller Generate an XML-RPC params chunk from a Python data structure
117 Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
118 Transport Handles an HTTP transaction to an XML-RPC server
119 SafeTransport Handles an HTTPS transaction to an XML-RPC server
Fred Drake1b410792001-09-04 18:55:03 +0000120
121Exported constants:
122
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000123 True
124 False
Fred Drake1b410792001-09-04 18:55:03 +0000125
126Exported functions:
127
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000128 getparser Create instance of the fastest available parser & attach
129 to an unmarshalling object
130 dumps Convert an argument tuple or a Fault instance to an XML-RPC
131 request (or response, if the methodresponse option is used).
132 loads Convert an XML-RPC packet to unmarshalled data plus a method
133 name (None if not present).
Fred Drake1b410792001-09-04 18:55:03 +0000134"""
135
Neal Norwitzff113342007-04-17 08:42:15 +0000136import re, time, operator
Georg Brandl24420152008-05-26 16:32:26 +0000137import http.client
Georg Brandlcef803f2009-06-04 09:04:53 +0000138from xml.parsers import expat
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000139import socket
140import errno
141from io import BytesIO
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +0000142try:
143 import gzip
144except ImportError:
145 gzip = None #python can be built without zlib/gzip support
Fredrik Lundh1538c232001-10-01 19:42:03 +0000146
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000147# --------------------------------------------------------------------
148# Internal stuff
149
Fredrik Lundhb9056332001-07-11 17:42:21 +0000150try:
Fred Drakeba613c32005-02-10 18:33:30 +0000151 import datetime
152except ImportError:
153 datetime = None
154
Neal Norwitzff113342007-04-17 08:42:15 +0000155def escape(s):
156 s = s.replace("&", "&")
157 s = s.replace("<", "&lt;")
158 return s.replace(">", "&gt;",)
Fredrik Lundh1538c232001-10-01 19:42:03 +0000159
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000160__version__ = "1.0.1"
161
162# xmlrpc integer limits
Guido van Rossume2a383d2007-01-15 16:59:06 +0000163MAXINT = 2**31-1
164MININT = -2**31
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000165
166# --------------------------------------------------------------------
167# Error constants (from Dan Libby's specification at
168# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
169
170# Ranges of errors
171PARSE_ERROR = -32700
172SERVER_ERROR = -32600
173APPLICATION_ERROR = -32500
174SYSTEM_ERROR = -32400
175TRANSPORT_ERROR = -32300
176
177# Specific errors
178NOT_WELLFORMED_ERROR = -32700
179UNSUPPORTED_ENCODING = -32701
180INVALID_ENCODING_CHAR = -32702
181INVALID_XMLRPC = -32600
182METHOD_NOT_FOUND = -32601
183INVALID_METHOD_PARAMS = -32602
184INTERNAL_ERROR = -32603
Fredrik Lundhb9056332001-07-11 17:42:21 +0000185
186# --------------------------------------------------------------------
187# Exceptions
188
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000189##
190# Base class for all kinds of client-side errors.
191
Fredrik Lundh78eedce2001-08-23 20:04:33 +0000192class Error(Exception):
Fred Drake1b410792001-09-04 18:55:03 +0000193 """Base class for client errors."""
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000194 def __str__(self):
195 return repr(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000196
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000197##
198# Indicates an HTTP-level protocol error. This is raised by the HTTP
199# transport layer, if the server returns an error code other than 200
200# (OK).
201#
202# @param url The target URL.
203# @param errcode The HTTP error code.
204# @param errmsg The HTTP error message.
205# @param headers The HTTP header dictionary.
206
Fredrik Lundhb9056332001-07-11 17:42:21 +0000207class ProtocolError(Error):
Fred Drake1b410792001-09-04 18:55:03 +0000208 """Indicates an HTTP protocol error."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000209 def __init__(self, url, errcode, errmsg, headers):
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000210 Error.__init__(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000211 self.url = url
212 self.errcode = errcode
213 self.errmsg = errmsg
214 self.headers = headers
215 def __repr__(self):
216 return (
217 "<ProtocolError for %s: %s %s>" %
218 (self.url, self.errcode, self.errmsg)
219 )
220
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000221##
222# Indicates a broken XML-RPC response package. This exception is
223# raised by the unmarshalling layer, if the XML-RPC response is
224# malformed.
225
Fredrik Lundhb9056332001-07-11 17:42:21 +0000226class ResponseError(Error):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000227 """Indicates a broken response package."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000228 pass
229
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000230##
231# Indicates an XML-RPC fault response package. This exception is
232# raised by the unmarshalling layer, if the XML-RPC response contains
233# a fault string. This exception can also used as a class, to
234# generate a fault XML-RPC message.
235#
236# @param faultCode The XML-RPC fault code.
237# @param faultString The XML-RPC fault string.
238
Fredrik Lundhb9056332001-07-11 17:42:21 +0000239class Fault(Error):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000240 """Indicates an XML-RPC fault package."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000241 def __init__(self, faultCode, faultString, **extra):
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000242 Error.__init__(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000243 self.faultCode = faultCode
244 self.faultString = faultString
245 def __repr__(self):
246 return (
247 "<Fault %s: %s>" %
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000248 (self.faultCode, repr(self.faultString))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000249 )
250
251# --------------------------------------------------------------------
252# Special values
253
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000254##
Georg Brandl38eceaa2008-05-26 11:14:17 +0000255# Backwards compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000256
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000257boolean = Boolean = bool
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000258
259##
260# Wrapper for XML-RPC DateTime values. This converts a time value to
261# the format used by XML-RPC.
262# <p>
263# The value can be given as a string in the format
264# "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
265# time.localtime()), or an integer value (as returned by time.time()).
266# The wrapper uses time.localtime() to convert an integer to a time
267# tuple.
268#
269# @param value The time, given as an ISO 8601 string, a time
270# tuple, or a integer time value.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000271
Christian Heimesdae2a892008-04-19 00:55:37 +0000272def _strftime(value):
273 if datetime:
274 if isinstance(value, datetime.datetime):
275 return "%04d%02d%02dT%02d:%02d:%02d" % (
276 value.year, value.month, value.day,
277 value.hour, value.minute, value.second)
278
279 if not isinstance(value, (tuple, time.struct_time)):
280 if value == 0:
281 value = time.time()
282 value = time.localtime(value)
283
284 return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
285
Fredrik Lundhb9056332001-07-11 17:42:21 +0000286class DateTime:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000287 """DateTime wrapper for an ISO 8601 string or time tuple or
288 localtime integer value to generate 'dateTime.iso8601' XML-RPC
289 value.
290 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000291
292 def __init__(self, value=0):
Christian Heimesdae2a892008-04-19 00:55:37 +0000293 if isinstance(value, str):
294 self.value = value
295 else:
296 self.value = _strftime(value)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000297
Christian Heimes05e8be12008-02-23 18:30:17 +0000298 def make_comparable(self, other):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000299 if isinstance(other, DateTime):
Christian Heimes05e8be12008-02-23 18:30:17 +0000300 s = self.value
301 o = other.value
302 elif datetime and isinstance(other, datetime.datetime):
303 s = self.value
304 o = other.strftime("%Y%m%dT%H:%M:%S")
305 elif isinstance(other, (str, unicode)):
306 s = self.value
307 o = other
308 elif hasattr(other, "timetuple"):
309 s = self.timetuple()
310 o = other.timetuple()
311 else:
312 otype = (hasattr(other, "__class__")
313 and other.__class__.__name__
314 or type(other))
315 raise TypeError("Can't compare %s and %s" %
316 (self.__class__.__name__, otype))
317 return s, o
318
319 def __lt__(self, other):
320 s, o = self.make_comparable(other)
321 return s < o
322
323 def __le__(self, other):
324 s, o = self.make_comparable(other)
325 return s <= o
326
327 def __gt__(self, other):
328 s, o = self.make_comparable(other)
329 return s > o
330
331 def __ge__(self, other):
332 s, o = self.make_comparable(other)
333 return s >= o
334
335 def __eq__(self, other):
336 s, o = self.make_comparable(other)
337 return s == o
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000338
339 def __ne__(self, other):
Christian Heimes05e8be12008-02-23 18:30:17 +0000340 s, o = self.make_comparable(other)
341 return s != o
342
343 def timetuple(self):
344 return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
345
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000346 ##
347 # Get date/time value.
348 #
349 # @return Date/time value, as an ISO 8601 string.
350
351 def __str__(self):
352 return self.value
353
Fredrik Lundhb9056332001-07-11 17:42:21 +0000354 def __repr__(self):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000355 return "<DateTime %s at %x>" % (repr(self.value), id(self))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000356
357 def decode(self, data):
Neal Norwitzff113342007-04-17 08:42:15 +0000358 self.value = str(data).strip()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000359
360 def encode(self, out):
361 out.write("<value><dateTime.iso8601>")
362 out.write(self.value)
363 out.write("</dateTime.iso8601></value>\n")
364
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000365def _datetime(data):
366 # decode xml element contents into a DateTime structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000367 value = DateTime()
368 value.decode(data)
369 return value
370
Skip Montanaro174dd222005-05-14 20:54:16 +0000371def _datetime_type(data):
372 t = time.strptime(data, "%Y%m%dT%H:%M:%S")
373 return datetime.datetime(*tuple(t)[:6])
374
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000375##
376# Wrapper for binary data. This can be used to transport any kind
377# of binary data over XML-RPC, using BASE64 encoding.
378#
379# @param data An 8-bit string containing arbitrary data.
380
Skip Montanarobfcbfa72003-04-24 19:51:31 +0000381import base64
Guido van Rossum68937b42007-05-18 00:51:22 +0000382import io
Skip Montanarobfcbfa72003-04-24 19:51:31 +0000383
Fredrik Lundhb9056332001-07-11 17:42:21 +0000384class Binary:
Fred Drake1b410792001-09-04 18:55:03 +0000385 """Wrapper for binary data."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000386
387 def __init__(self, data=None):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000388 if data is None:
389 data = b""
390 else:
391 if not isinstance(data, bytes):
392 raise TypeError("expected bytes, not %s" %
393 data.__class__.__name__)
394 data = bytes(data) # Make a copy of the bytes!
Fredrik Lundhb9056332001-07-11 17:42:21 +0000395 self.data = data
396
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000397 ##
398 # Get buffer contents.
399 #
400 # @return Buffer contents, as an 8-bit string.
401
402 def __str__(self):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000403 return str(self.data, "latin-1") # XXX encoding?!
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000404
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000405 def __eq__(self, other):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000406 if isinstance(other, Binary):
407 other = other.data
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000408 return self.data == other
409
410 def __ne__(self, other):
411 if isinstance(other, Binary):
412 other = other.data
413 return self.data != other
Fredrik Lundhb9056332001-07-11 17:42:21 +0000414
415 def decode(self, data):
Georg Brandlb54d8012009-06-04 09:11:51 +0000416 self.data = base64.decodebytes(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000417
418 def encode(self, out):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000419 out.write("<value><base64>\n")
Georg Brandlb54d8012009-06-04 09:11:51 +0000420 encoded = base64.encodebytes(self.data)
Brett Cannon2dbde5e2007-07-30 03:50:35 +0000421 out.write(encoded.decode('ascii'))
422 out.write('\n')
Fredrik Lundhb9056332001-07-11 17:42:21 +0000423 out.write("</base64></value>\n")
424
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000425def _binary(data):
426 # decode xml element contents into a Binary structure
Fredrik Lundhb9056332001-07-11 17:42:21 +0000427 value = Binary()
428 value.decode(data)
429 return value
430
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000431WRAPPERS = (DateTime, Binary)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000432
433# --------------------------------------------------------------------
434# XML parsers
435
Georg Brandlcef803f2009-06-04 09:04:53 +0000436class ExpatParser:
437 # fast expat parser for Python 2.0 and later.
438 def __init__(self, target):
439 self._parser = parser = expat.ParserCreate(None, None)
440 self._target = target
441 parser.StartElementHandler = target.start
442 parser.EndElementHandler = target.end
443 parser.CharacterDataHandler = target.data
444 encoding = None
445 target.xml(encoding, None)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000446
Georg Brandlcef803f2009-06-04 09:04:53 +0000447 def feed(self, data):
448 self._parser.Parse(data, 0)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000449
Georg Brandlcef803f2009-06-04 09:04:53 +0000450 def close(self):
451 self._parser.Parse("", 1) # end of data
452 del self._target, self._parser # get rid of circular references
Fredrik Lundhb9056332001-07-11 17:42:21 +0000453
Fredrik Lundhb9056332001-07-11 17:42:21 +0000454# --------------------------------------------------------------------
455# XML-RPC marshalling and unmarshalling code
456
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000457##
458# XML-RPC marshaller.
459#
460# @param encoding Default encoding for 8-bit strings. The default
461# value is None (interpreted as UTF-8).
462# @see dumps
463
Fredrik Lundhb9056332001-07-11 17:42:21 +0000464class Marshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000465 """Generate an XML-RPC params chunk from a Python data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000466
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000467 Create a Marshaller instance for each set of parameters, and use
468 the "dumps" method to convert your data (represented as a tuple)
469 to an XML-RPC params chunk. To write a fault response, pass a
470 Fault instance instead. You may prefer to use the "dumps" module
471 function for this purpose.
Fred Drake1b410792001-09-04 18:55:03 +0000472 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000473
474 # by the way, if you don't understand what's going on in here,
475 # that's perfectly ok.
476
Georg Brandlfe991052009-09-16 15:54:04 +0000477 def __init__(self, encoding=None, allow_none=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000478 self.memo = {}
479 self.data = None
480 self.encoding = encoding
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000481 self.allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +0000482
Fredrik Lundhb9056332001-07-11 17:42:21 +0000483 dispatch = {}
484
485 def dumps(self, values):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000486 out = []
487 write = out.append
488 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000489 if isinstance(values, Fault):
490 # fault instance
491 write("<fault>\n")
Martin v. Löwis541342f2003-07-12 07:53:04 +0000492 dump({'faultCode': values.faultCode,
493 'faultString': values.faultString},
494 write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000495 write("</fault>\n")
496 else:
497 # parameter block
Fredrik Lundhc266bb02001-08-23 20:13:08 +0000498 # FIXME: the xml-rpc specification allows us to leave out
499 # the entire <params> block if there are no parameters.
500 # however, changing this may break older code (including
501 # old versions of xmlrpclib.py), so this is better left as
502 # is for now. See @XMLRPC3 for more information. /F
Fredrik Lundhb9056332001-07-11 17:42:21 +0000503 write("<params>\n")
504 for v in values:
505 write("<param>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000506 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000507 write("</param>\n")
508 write("</params>\n")
Neal Norwitzff113342007-04-17 08:42:15 +0000509 result = "".join(out)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000510 return result
511
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000512 def __dump(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000513 try:
514 f = self.dispatch[type(value)]
515 except KeyError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000516 # check if this object can be marshalled as a structure
517 try:
518 value.__dict__
519 except:
Collin Winterce36ad82007-08-30 01:19:48 +0000520 raise TypeError("cannot marshal %s objects" % type(value))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000521 # check if this class is a sub-class of a basic type,
522 # because we don't know how to marshal these types
523 # (e.g. a string sub-class)
524 for type_ in type(value).__mro__:
525 if type_ in self.dispatch.keys():
Collin Winterce36ad82007-08-30 01:19:48 +0000526 raise TypeError("cannot marshal %s objects" % type(value))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000527 # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
528 # for the p3yk merge, this should probably be fixed more neatly.
529 f = self.dispatch["_arbitrary_instance"]
530 f(self, value, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000531
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000532 def dump_nil (self, value, write):
533 if not self.allow_none:
Collin Winterce36ad82007-08-30 01:19:48 +0000534 raise TypeError("cannot marshal None unless allow_none is enabled")
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000535 write("<value><nil/></value>")
Guido van Rossum13257902007-06-07 23:15:56 +0000536 dispatch[type(None)] = dump_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000537
Georg Brandl38eceaa2008-05-26 11:14:17 +0000538 def dump_bool(self, value, write):
539 write("<value><boolean>")
540 write(value and "1" or "0")
541 write("</boolean></value>\n")
542 dispatch[bool] = dump_bool
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000543
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000544 def dump_long(self, value, write):
Skip Montanaro5449e082001-10-17 22:53:33 +0000545 if value > MAXINT or value < MININT:
Collin Winterce36ad82007-08-30 01:19:48 +0000546 raise OverflowError("long int exceeds XML-RPC limits")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000547 write("<value><int>")
548 write(str(int(value)))
549 write("</int></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000550 dispatch[int] = dump_long
Skip Montanaro5e9c71b2001-10-10 15:56:34 +0000551
Florent Xicluna2bb96f52011-10-23 22:11:00 +0200552 # backward compatible
553 dump_int = dump_long
554
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000555 def dump_double(self, value, write):
556 write("<value><double>")
557 write(repr(value))
558 write("</double></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000559 dispatch[float] = dump_double
Fredrik Lundhb9056332001-07-11 17:42:21 +0000560
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000561 def dump_string(self, value, write, escape=escape):
562 write("<value><string>")
563 write(escape(value))
564 write("</string></value>\n")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000565 dispatch[bytes] = dump_string
Fredrik Lundhb9056332001-07-11 17:42:21 +0000566
Guido van Rossum54ad5232007-05-27 09:17:48 +0000567 def dump_unicode(self, value, write, escape=escape):
Guido van Rossum54ad5232007-05-27 09:17:48 +0000568 write("<value><string>")
569 write(escape(value))
570 write("</string></value>\n")
571 dispatch[str] = dump_unicode
Fredrik Lundhb9056332001-07-11 17:42:21 +0000572
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000573 def dump_array(self, value, write):
574 i = id(value)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000575 if i in self.memo:
Collin Winterce36ad82007-08-30 01:19:48 +0000576 raise TypeError("cannot marshal recursive sequences")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000577 self.memo[i] = None
Fredrik Lundh1538c232001-10-01 19:42:03 +0000578 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000579 write("<value><array><data>\n")
580 for v in value:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000581 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000582 write("</data></array></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000583 del self.memo[i]
Guido van Rossum13257902007-06-07 23:15:56 +0000584 dispatch[tuple] = dump_array
585 dispatch[list] = dump_array
Fredrik Lundhb9056332001-07-11 17:42:21 +0000586
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000587 def dump_struct(self, value, write, escape=escape):
588 i = id(value)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000589 if i in self.memo:
Collin Winterce36ad82007-08-30 01:19:48 +0000590 raise TypeError("cannot marshal recursive dictionaries")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000591 self.memo[i] = None
Fredrik Lundh1538c232001-10-01 19:42:03 +0000592 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000593 write("<value><struct>\n")
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000594 for k, v in value.items():
Fredrik Lundhb9056332001-07-11 17:42:21 +0000595 write("<member>\n")
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000596 if not isinstance(k, str):
Collin Winterce36ad82007-08-30 01:19:48 +0000597 raise TypeError("dictionary key must be string")
Fredrik Lundh1538c232001-10-01 19:42:03 +0000598 write("<name>%s</name>\n" % escape(k))
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000599 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000600 write("</member>\n")
601 write("</struct></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000602 del self.memo[i]
Guido van Rossum13257902007-06-07 23:15:56 +0000603 dispatch[dict] = dump_struct
Fredrik Lundhb9056332001-07-11 17:42:21 +0000604
Fred Drakeba613c32005-02-10 18:33:30 +0000605 if datetime:
606 def dump_datetime(self, value, write):
607 write("<value><dateTime.iso8601>")
Christian Heimesdae2a892008-04-19 00:55:37 +0000608 write(_strftime(value))
Fred Drakeba613c32005-02-10 18:33:30 +0000609 write("</dateTime.iso8601></value>\n")
610 dispatch[datetime.datetime] = dump_datetime
611
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000612 def dump_instance(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000613 # check for special wrappers
614 if value.__class__ in WRAPPERS:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000615 self.write = write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000616 value.encode(self)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000617 del self.write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000618 else:
619 # store instance attributes as a struct (really?)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000620 self.dump_struct(value.__dict__, write)
Guido van Rossume4dea982006-04-21 13:45:00 +0000621 dispatch[DateTime] = dump_instance
622 dispatch[Binary] = dump_instance
Thomas Wouters89f507f2006-12-13 04:49:30 +0000623 # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
624 # for the p3yk merge, this should probably be fixed more neatly.
625 dispatch["_arbitrary_instance"] = dump_instance
Fredrik Lundhb9056332001-07-11 17:42:21 +0000626
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000627##
628# XML-RPC unmarshaller.
629#
630# @see loads
631
Fredrik Lundhb9056332001-07-11 17:42:21 +0000632class Unmarshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000633 """Unmarshal an XML-RPC response, based on incoming XML event
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000634 messages (start, data, end). Call close() to get the resulting
Fred Drake1b410792001-09-04 18:55:03 +0000635 data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000636
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000637 Note that this reader is fairly tolerant, and gladly accepts bogus
638 XML-RPC data without complaining (but not bogus XML).
Fred Drake1b410792001-09-04 18:55:03 +0000639 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000640
641 # and again, if you don't understand what's going on in here,
642 # that's perfectly ok.
643
Georg Brandlfe991052009-09-16 15:54:04 +0000644 def __init__(self, use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000645 self._type = None
646 self._stack = []
647 self._marks = []
648 self._data = []
649 self._methodname = None
650 self._encoding = "utf-8"
651 self.append = self._stack.append
Skip Montanaro174dd222005-05-14 20:54:16 +0000652 self._use_datetime = use_datetime
653 if use_datetime and not datetime:
Collin Winterce36ad82007-08-30 01:19:48 +0000654 raise ValueError("the datetime module is not available")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000655
656 def close(self):
657 # return response tuple and target method
658 if self._type is None or self._marks:
659 raise ResponseError()
660 if self._type == "fault":
Guido van Rossum68468eb2003-02-27 20:14:51 +0000661 raise Fault(**self._stack[0])
Fredrik Lundhb9056332001-07-11 17:42:21 +0000662 return tuple(self._stack)
663
664 def getmethodname(self):
665 return self._methodname
666
667 #
668 # event handlers
669
670 def xml(self, encoding, standalone):
671 self._encoding = encoding
672 # FIXME: assert standalone == 1 ???
673
674 def start(self, tag, attrs):
675 # prepare to handle this element
676 if tag == "array" or tag == "struct":
677 self._marks.append(len(self._stack))
678 self._data = []
679 self._value = (tag == "value")
680
681 def data(self, text):
682 self._data.append(text)
683
Neal Norwitzff113342007-04-17 08:42:15 +0000684 def end(self, tag):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000685 # call the appropriate end tag handler
686 try:
687 f = self.dispatch[tag]
688 except KeyError:
689 pass # unknown tag ?
690 else:
Neal Norwitzff113342007-04-17 08:42:15 +0000691 return f(self, "".join(self._data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000692
693 #
694 # accelerator support
695
696 def end_dispatch(self, tag, data):
697 # dispatch data
698 try:
699 f = self.dispatch[tag]
700 except KeyError:
701 pass # unknown tag ?
702 else:
703 return f(self, data)
704
705 #
706 # element decoders
707
708 dispatch = {}
709
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000710 def end_nil (self, data):
711 self.append(None)
712 self._value = 0
713 dispatch["nil"] = end_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000714
Fredrik Lundh1538c232001-10-01 19:42:03 +0000715 def end_boolean(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000716 if data == "0":
717 self.append(False)
718 elif data == "1":
719 self.append(True)
720 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000721 raise TypeError("bad boolean value")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000722 self._value = 0
723 dispatch["boolean"] = end_boolean
724
Fredrik Lundh1538c232001-10-01 19:42:03 +0000725 def end_int(self, data):
726 self.append(int(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000727 self._value = 0
728 dispatch["i4"] = end_int
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000729 dispatch["i8"] = end_int
Fredrik Lundhb9056332001-07-11 17:42:21 +0000730 dispatch["int"] = end_int
731
Fredrik Lundh1538c232001-10-01 19:42:03 +0000732 def end_double(self, data):
733 self.append(float(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000734 self._value = 0
735 dispatch["double"] = end_double
736
Fredrik Lundh1538c232001-10-01 19:42:03 +0000737 def end_string(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000738 if self._encoding:
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000739 data = data.decode(self._encoding)
740 self.append(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000741 self._value = 0
742 dispatch["string"] = end_string
743 dispatch["name"] = end_string # struct keys are always strings
744
745 def end_array(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000746 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000747 # map arrays to Python lists
748 self._stack[mark:] = [self._stack[mark:]]
749 self._value = 0
750 dispatch["array"] = end_array
751
752 def end_struct(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000753 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000754 # map structs to Python dictionaries
755 dict = {}
756 items = self._stack[mark:]
757 for i in range(0, len(items), 2):
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000758 dict[items[i]] = items[i+1]
Fredrik Lundhb9056332001-07-11 17:42:21 +0000759 self._stack[mark:] = [dict]
760 self._value = 0
761 dispatch["struct"] = end_struct
762
Fredrik Lundh1538c232001-10-01 19:42:03 +0000763 def end_base64(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000764 value = Binary()
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000765 value.decode(data.encode("ascii"))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000766 self.append(value)
767 self._value = 0
768 dispatch["base64"] = end_base64
769
Fredrik Lundh1538c232001-10-01 19:42:03 +0000770 def end_dateTime(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000771 value = DateTime()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000772 value.decode(data)
Skip Montanaro174dd222005-05-14 20:54:16 +0000773 if self._use_datetime:
774 value = _datetime_type(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000775 self.append(value)
776 dispatch["dateTime.iso8601"] = end_dateTime
777
778 def end_value(self, data):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000779 # if we stumble upon a value element with no internal
Fredrik Lundhb9056332001-07-11 17:42:21 +0000780 # elements, treat it as a string element
781 if self._value:
782 self.end_string(data)
783 dispatch["value"] = end_value
784
785 def end_params(self, data):
786 self._type = "params"
787 dispatch["params"] = end_params
788
789 def end_fault(self, data):
790 self._type = "fault"
791 dispatch["fault"] = end_fault
792
Fredrik Lundh1538c232001-10-01 19:42:03 +0000793 def end_methodName(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000794 if self._encoding:
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000795 data = data.decode(self._encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000796 self._methodname = data
797 self._type = "methodName" # no params
798 dispatch["methodName"] = end_methodName
799
Martin v. Löwis45394c22003-10-31 13:49:36 +0000800## Multicall support
801#
Fredrik Lundhb9056332001-07-11 17:42:21 +0000802
Martin v. Löwis45394c22003-10-31 13:49:36 +0000803class _MultiCallMethod:
804 # some lesser magic to store calls made to a MultiCall object
805 # for batch execution
806 def __init__(self, call_list, name):
807 self.__call_list = call_list
808 self.__name = name
809 def __getattr__(self, name):
810 return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
811 def __call__(self, *args):
812 self.__call_list.append((self.__name, args))
813
Martin v. Löwis12237b32004-08-22 16:04:50 +0000814class MultiCallIterator:
Martin v. Löwis45394c22003-10-31 13:49:36 +0000815 """Iterates over the results of a multicall. Exceptions are
816 thrown in response to xmlrpc faults."""
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000817
Martin v. Löwis12237b32004-08-22 16:04:50 +0000818 def __init__(self, results):
819 self.results = results
820
821 def __getitem__(self, i):
822 item = self.results[i]
823 if type(item) == type({}):
824 raise Fault(item['faultCode'], item['faultString'])
825 elif type(item) == type([]):
826 return item[0]
Martin v. Löwis45394c22003-10-31 13:49:36 +0000827 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000828 raise ValueError("unexpected type in multicall result")
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000829
Martin v. Löwis45394c22003-10-31 13:49:36 +0000830class MultiCall:
831 """server -> a object used to boxcar method calls
832
833 server should be a ServerProxy object.
834
835 Methods can be added to the MultiCall using normal
836 method call syntax e.g.:
837
838 multicall = MultiCall(server_proxy)
839 multicall.add(2,3)
840 multicall.get_address("Guido")
841
842 To execute the multicall, call the MultiCall object e.g.:
843
844 add_result, address = multicall()
845 """
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000846
Martin v. Löwis45394c22003-10-31 13:49:36 +0000847 def __init__(self, server):
848 self.__server = server
849 self.__call_list = []
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000850
Martin v. Löwis45394c22003-10-31 13:49:36 +0000851 def __repr__(self):
852 return "<MultiCall at %x>" % id(self)
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000853
Martin v. Löwis45394c22003-10-31 13:49:36 +0000854 __str__ = __repr__
855
856 def __getattr__(self, name):
857 return _MultiCallMethod(self.__call_list, name)
858
859 def __call__(self):
860 marshalled_list = []
861 for name, args in self.__call_list:
862 marshalled_list.append({'methodName' : name, 'params' : args})
863
864 return MultiCallIterator(self.__server.system.multicall(marshalled_list))
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000865
Fredrik Lundhb9056332001-07-11 17:42:21 +0000866# --------------------------------------------------------------------
867# convenience functions
868
Georg Brandl38eceaa2008-05-26 11:14:17 +0000869FastMarshaller = FastParser = FastUnmarshaller = None
870
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000871##
872# Create a parser object, and connect it to an unmarshalling instance.
873# This function picks the fastest available XML parser.
874#
875# return A (parser, unmarshaller) tuple.
876
Georg Brandlfe991052009-09-16 15:54:04 +0000877def getparser(use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000878 """getparser() -> parser, unmarshaller
879
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000880 Create an instance of the fastest available parser, and attach it
881 to an unmarshalling object. Return both objects.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000882 """
Skip Montanaro174dd222005-05-14 20:54:16 +0000883 if use_datetime and not datetime:
Collin Winterce36ad82007-08-30 01:19:48 +0000884 raise ValueError("the datetime module is not available")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000885 if FastParser and FastUnmarshaller:
Skip Montanaro174dd222005-05-14 20:54:16 +0000886 if use_datetime:
887 mkdatetime = _datetime_type
888 else:
889 mkdatetime = _datetime
890 target = FastUnmarshaller(True, False, _binary, mkdatetime, Fault)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000891 parser = FastParser(target)
892 else:
Skip Montanaro174dd222005-05-14 20:54:16 +0000893 target = Unmarshaller(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000894 if FastParser:
895 parser = FastParser(target)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000896 else:
Georg Brandlcef803f2009-06-04 09:04:53 +0000897 parser = ExpatParser(target)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000898 return parser, target
899
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000900##
901# Convert a Python tuple or a Fault instance to an XML-RPC packet.
902#
903# @def dumps(params, **options)
904# @param params A tuple or Fault instance.
905# @keyparam methodname If given, create a methodCall request for
906# this method name.
907# @keyparam methodresponse If given, create a methodResponse packet.
908# If used with a tuple, the tuple must be a singleton (that is,
909# it must contain exactly one element).
910# @keyparam encoding The packet encoding.
911# @return A string containing marshalled data.
912
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000913def dumps(params, methodname=None, methodresponse=None, encoding=None,
Georg Brandlfe991052009-09-16 15:54:04 +0000914 allow_none=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000915 """data [,options] -> marshalled data
916
917 Convert an argument tuple or a Fault instance to an XML-RPC
918 request (or response, if the methodresponse option is used).
919
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000920 In addition to the data object, the following options can be given
921 as keyword arguments:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000922
923 methodname: the method name for a methodCall packet
924
925 methodresponse: true to create a methodResponse packet.
926 If this option is used with a tuple, the tuple must be
927 a singleton (i.e. it can contain only one element).
928
929 encoding: the packet encoding (default is UTF-8)
930
931 All 8-bit strings in the data structure are assumed to use the
932 packet encoding. Unicode strings are automatically converted,
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000933 where necessary.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000934 """
935
Guido van Rossum13257902007-06-07 23:15:56 +0000936 assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
Fredrik Lundhb9056332001-07-11 17:42:21 +0000937 if isinstance(params, Fault):
938 methodresponse = 1
Guido van Rossum13257902007-06-07 23:15:56 +0000939 elif methodresponse and isinstance(params, tuple):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000940 assert len(params) == 1, "response tuple must be a singleton"
941
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000942 if not encoding:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000943 encoding = "utf-8"
944
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000945 if FastMarshaller:
946 m = FastMarshaller(encoding)
947 else:
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000948 m = Marshaller(encoding, allow_none)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000949
Fredrik Lundhb9056332001-07-11 17:42:21 +0000950 data = m.dumps(params)
951
952 if encoding != "utf-8":
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000953 xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000954 else:
955 xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
956
957 # standard XML-RPC wrappings
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000958 if methodname:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000959 # a method call
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000960 if not isinstance(methodname, str):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000961 methodname = methodname.encode(encoding)
962 data = (
963 xmlheader,
964 "<methodCall>\n"
965 "<methodName>", methodname, "</methodName>\n",
966 data,
967 "</methodCall>\n"
968 )
969 elif methodresponse:
970 # a method response, or a fault structure
971 data = (
972 xmlheader,
973 "<methodResponse>\n",
974 data,
975 "</methodResponse>\n"
976 )
977 else:
978 return data # return as is
Neal Norwitzff113342007-04-17 08:42:15 +0000979 return "".join(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000980
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000981##
982# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
983# represents a fault condition, this function raises a Fault exception.
984#
985# @param data An XML-RPC packet, given as an 8-bit string.
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000986# @return A tuple containing the unpacked data, and the method name
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000987# (None if not present).
988# @see Fault
989
Georg Brandlfe991052009-09-16 15:54:04 +0000990def loads(data, use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000991 """data -> unmarshalled data, method name
992
993 Convert an XML-RPC packet to unmarshalled data plus a method
994 name (None if not present).
995
996 If the XML-RPC packet represents a fault condition, this function
997 raises a Fault exception.
998 """
Skip Montanaro174dd222005-05-14 20:54:16 +0000999 p, u = getparser(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001000 p.feed(data)
1001 p.close()
1002 return u.close(), u.getmethodname()
1003
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001004##
1005# Encode a string using the gzip content encoding such as specified by the
1006# Content-Encoding: gzip
1007# in the HTTP header, as described in RFC 1952
1008#
1009# @param data the unencoded data
1010# @return the encoded data
1011
1012def gzip_encode(data):
1013 """data -> gzip encoded data
1014
1015 Encode data using the gzip content encoding as described in RFC 1952
1016 """
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001017 if not gzip:
1018 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001019 f = BytesIO()
1020 gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
1021 gzf.write(data)
1022 gzf.close()
1023 encoded = f.getvalue()
1024 f.close()
1025 return encoded
1026
1027##
1028# Decode a string using the gzip content encoding such as specified by the
1029# Content-Encoding: gzip
1030# in the HTTP header, as described in RFC 1952
1031#
1032# @param data The encoded data
1033# @return the unencoded data
1034# @raises ValueError if data is not correctly coded.
1035
1036def gzip_decode(data):
1037 """gzip encoded data -> unencoded data
1038
1039 Decode data using the gzip content encoding as described in RFC 1952
1040 """
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001041 if not gzip:
1042 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001043 f = BytesIO(data)
1044 gzf = gzip.GzipFile(mode="rb", fileobj=f)
1045 try:
1046 decoded = gzf.read()
1047 except IOError:
1048 raise ValueError("invalid data")
1049 f.close()
1050 gzf.close()
1051 return decoded
1052
1053##
1054# Return a decoded file-like object for the gzip encoding
1055# as described in RFC 1952.
1056#
1057# @param response A stream supporting a read() method
1058# @return a file-like object that the decoded data can be read() from
1059
Kristján Valur Jónsson9ab07312009-07-19 22:38:38 +00001060class GzipDecodedResponse(gzip.GzipFile if gzip else object):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001061 """a file-like object to decode a response encoded with the gzip
1062 method, as described in RFC 1952.
1063 """
1064 def __init__(self, response):
1065 #response doesn't support tell() and read(), required by
1066 #GzipFile
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001067 if not gzip:
1068 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001069 self.io = BytesIO(response.read())
1070 gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io)
1071
1072 def close(self):
1073 gzip.GzipFile.close(self)
1074 self.io.close()
1075
Fredrik Lundhb9056332001-07-11 17:42:21 +00001076
1077# --------------------------------------------------------------------
1078# request dispatcher
1079
1080class _Method:
1081 # some magic to bind an XML-RPC method to an RPC server.
1082 # supports "nested" methods (e.g. examples.getStateName)
1083 def __init__(self, send, name):
1084 self.__send = send
1085 self.__name = name
1086 def __getattr__(self, name):
1087 return _Method(self.__send, "%s.%s" % (self.__name, name))
1088 def __call__(self, *args):
1089 return self.__send(self.__name, args)
1090
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001091##
1092# Standard transport class for XML-RPC over HTTP.
1093# <p>
1094# You can create custom transports by subclassing this method, and
1095# overriding selected methods.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001096
1097class Transport:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001098 """Handles an HTTP transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001099
1100 # client identifier (may be overridden)
1101 user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
1102
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001103 #if true, we'll request gzip encoding
1104 accept_gzip_encoding = True
1105
1106 # if positive, encode request using gzip if it exceeds this threshold
1107 # note that many server will get confused, so only use it if you know
1108 # that they can decode such a request
1109 encode_threshold = None #None = don't encode
1110
Georg Brandlfe991052009-09-16 15:54:04 +00001111 def __init__(self, use_datetime=False):
Skip Montanaro174dd222005-05-14 20:54:16 +00001112 self._use_datetime = use_datetime
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001113 self._connection = (None, None)
1114 self._extra_headers = []
Skip Montanaro174dd222005-05-14 20:54:16 +00001115
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001116 ##
1117 # Send a complete request, and parse the response.
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001118 # Retry request if a cached connection has disconnected.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001119 #
1120 # @param host Target host.
1121 # @param handler Target PRC handler.
1122 # @param request_body XML-RPC request body.
1123 # @param verbose Debugging flag.
1124 # @return Parsed response.
1125
Georg Brandlfe991052009-09-16 15:54:04 +00001126 def request(self, host, handler, request_body, verbose=False):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001127 #retry request once if cached connection has gone cold
1128 for i in (0, 1):
1129 try:
1130 return self.single_request(host, handler, request_body, verbose)
Kristján Valur Jónsson43535d92009-07-03 23:23:50 +00001131 except socket.error as e:
Victor Stinner756f5472010-07-24 02:24:55 +00001132 if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
Kristján Valur Jónsson43535d92009-07-03 23:23:50 +00001133 raise
1134 except http.client.BadStatusLine: #close after we sent request
1135 if i:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001136 raise
1137
Georg Brandlfe991052009-09-16 15:54:04 +00001138 def single_request(self, host, handler, request_body, verbose=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001139 # issue XML-RPC request
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001140 try:
1141 http_conn = self.send_request(host, handler, request_body, verbose)
1142 resp = http_conn.getresponse()
1143 if resp.status == 200:
1144 self.verbose = verbose
1145 return self.parse_response(resp)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001146
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001147 except Fault:
1148 raise
1149 except Exception:
1150 #All unexpected errors leave connection in
1151 # a strange state, so we clear it.
1152 self.close()
1153 raise
Fredrik Lundhb9056332001-07-11 17:42:21 +00001154
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001155 #We got an error response.
1156 #Discard any response data and raise exception
1157 if resp.getheader("content-length", ""):
1158 resp.read()
1159 raise ProtocolError(
1160 host + handler,
1161 resp.status, resp.reason,
1162 dict(resp.getheaders())
1163 )
Fredrik Lundhb9056332001-07-11 17:42:21 +00001164
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001165
1166 ##
1167 # Create parser.
1168 #
1169 # @return A 2-tuple containing a parser and a unmarshaller.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001170
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001171 def getparser(self):
1172 # get parser and unmarshaller
Skip Montanaro174dd222005-05-14 20:54:16 +00001173 return getparser(use_datetime=self._use_datetime)
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001174
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001175 ##
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001176 # Get authorization info from host parameter
1177 # Host may be a string, or a (host, x509-dict) tuple; if a string,
1178 # it is checked for a "user:pw@host" format, and a "Basic
1179 # Authentication" header is added if appropriate.
1180 #
1181 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1182 # @return A 3-tuple containing (actual host, extra headers,
1183 # x509 info). The header and x509 fields may be None.
1184
1185 def get_host_info(self, host):
1186
1187 x509 = {}
Guido van Rossum13257902007-06-07 23:15:56 +00001188 if isinstance(host, tuple):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001189 host, x509 = host
1190
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001191 import urllib.parse
1192 auth, host = urllib.parse.splituser(host)
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001193
1194 if auth:
1195 import base64
Georg Brandlc8dcfb62009-02-13 10:50:01 +00001196 auth = urllib.parse.unquote_to_bytes(auth)
Georg Brandlb54d8012009-06-04 09:11:51 +00001197 auth = base64.encodebytes(auth).decode("utf-8")
Neal Norwitzff113342007-04-17 08:42:15 +00001198 auth = "".join(auth.split()) # get rid of whitespace
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001199 extra_headers = [
1200 ("Authorization", "Basic " + auth)
1201 ]
1202 else:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001203 extra_headers = []
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001204
1205 return host, extra_headers, x509
1206
1207 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001208 # Connect to server.
1209 #
1210 # @param host Target host.
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001211 # @return An HTTPConnection object
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001212
Fredrik Lundhb9056332001-07-11 17:42:21 +00001213 def make_connection(self, host):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001214 #return an existing connection if possible. This allows
1215 #HTTP/1.1 keep-alive.
1216 if self._connection and host == self._connection[0]:
1217 return self._connection[1]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001218 # create a HTTP connection object from a host descriptor
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001219 chost, self._extra_headers, x509 = self.get_host_info(host)
1220 self._connection = host, http.client.HTTPConnection(chost)
1221 return self._connection[1]
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001222
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001223 ##
1224 # Clear any cached connection object.
1225 # Used in the event of socket errors.
1226 #
1227 def close(self):
1228 if self._connection[1]:
1229 self._connection[1].close()
1230 self._connection = (None, None)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001231
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001232 ##
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001233 # Send HTTP request.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001234 #
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001235 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1236 # @param handler Targer RPC handler (a path relative to host)
1237 # @param request_body The XML-RPC request body
1238 # @param debug Enable debugging if debug is true.
1239 # @return An HTTPConnection.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001240
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001241 def send_request(self, host, handler, request_body, debug):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001242 connection = self.make_connection(host)
1243 headers = self._extra_headers[:]
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001244 if debug:
1245 connection.set_debuglevel(1)
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001246 if self.accept_gzip_encoding and gzip:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001247 connection.putrequest("POST", handler, skip_accept_encoding=True)
1248 headers.append(("Accept-Encoding", "gzip"))
1249 else:
1250 connection.putrequest("POST", handler)
1251 headers.append(("Content-Type", "text/xml"))
1252 headers.append(("User-Agent", self.user_agent))
1253 self.send_headers(connection, headers)
1254 self.send_content(connection, request_body)
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001255 return connection
Fredrik Lundhb9056332001-07-11 17:42:21 +00001256
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001257 ##
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001258 # Send request headers.
1259 # This function provides a useful hook for subclassing
1260 #
1261 # @param connection httpConnection.
1262 # @param headers list of key,value pairs for HTTP headers
1263
1264 def send_headers(self, connection, headers):
1265 for key, val in headers:
1266 connection.putheader(key, val)
1267
1268 ##
1269 # Send request body.
1270 # This function provides a useful hook for subclassing
1271 #
1272 # @param connection httpConnection.
1273 # @param request_body XML-RPC request body.
1274
1275 def send_content(self, connection, request_body):
1276 #optionally encode the request
1277 if (self.encode_threshold is not None and
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001278 self.encode_threshold < len(request_body) and
1279 gzip):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001280 connection.putheader("Content-Encoding", "gzip")
1281 request_body = gzip_encode(request_body)
1282
1283 connection.putheader("Content-Length", str(len(request_body)))
1284 connection.endheaders(request_body)
1285
1286 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001287 # Parse response.
1288 #
1289 # @param file Stream.
1290 # @return Response tuple and target method.
1291
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001292 def parse_response(self, response):
1293 # read response data from httpresponse, and parse it
Senthil Kumaranf34445f2010-12-08 08:04:49 +00001294 # Check for new http response object, otherwise it is a file object.
1295 if hasattr(response, 'getheader'):
1296 if response.getheader("Content-Encoding", "") == "gzip":
1297 stream = GzipDecodedResponse(response)
1298 else:
1299 stream = response
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001300 else:
1301 stream = response
Fredrik Lundhb9056332001-07-11 17:42:21 +00001302
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001303 p, u = self.getparser()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001304
1305 while 1:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001306 data = stream.read(1024)
1307 if not data:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001308 break
1309 if self.verbose:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001310 print("body:", repr(data))
1311 p.feed(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001312
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001313 if stream is not response:
1314 stream.close()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001315 p.close()
1316
1317 return u.close()
1318
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001319##
1320# Standard transport class for XML-RPC over HTTPS.
1321
Fredrik Lundhb9056332001-07-11 17:42:21 +00001322class SafeTransport(Transport):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001323 """Handles an HTTPS transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001324
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001325 # FIXME: mostly untested
1326
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001327 def make_connection(self, host):
1328 if self._connection and host == self._connection[0]:
1329 return self._connection[1]
1330
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +00001331 if not hasattr(http.client, "HTTPSConnection"):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001332 raise NotImplementedError(
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001333 "your version of http.client doesn't support HTTPS")
1334 # create a HTTPS connection object from a host descriptor
1335 # host may be a string, or a (host, x509-dict) tuple
1336 chost, self._extra_headers, x509 = self.get_host_info(host)
1337 self._connection = host, http.client.HTTPSConnection(chost,
1338 None, **(x509 or {}))
1339 return self._connection[1]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001340
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001341##
1342# Standard server proxy. This class establishes a virtual connection
1343# to an XML-RPC server.
1344# <p>
1345# This class is available as ServerProxy and Server. New code should
1346# use ServerProxy, to avoid confusion.
1347#
1348# @def ServerProxy(uri, **options)
1349# @param uri The connection point on the server.
1350# @keyparam transport A transport factory, compatible with the
1351# standard transport class.
1352# @keyparam encoding The default encoding used for 8-bit strings
1353# (default is UTF-8).
1354# @keyparam verbose Use a true value to enable debugging output.
1355# (printed to standard output).
1356# @see Transport
1357
Fredrik Lundhb9056332001-07-11 17:42:21 +00001358class ServerProxy:
1359 """uri [,options] -> a logical connection to an XML-RPC server
1360
1361 uri is the connection point on the server, given as
1362 scheme://host/target.
1363
1364 The standard implementation always supports the "http" scheme. If
1365 SSL socket support is available (Python 2.0), it also supports
1366 "https".
1367
1368 If the target part and the slash preceding it are both omitted,
1369 "/RPC2" is assumed.
1370
1371 The following options can be given as keyword arguments:
1372
1373 transport: a transport factory
1374 encoding: the request encoding (default is UTF-8)
1375
1376 All 8-bit strings passed to the server proxy are assumed to use
1377 the given encoding.
1378 """
1379
Georg Brandlfe991052009-09-16 15:54:04 +00001380 def __init__(self, uri, transport=None, encoding=None, verbose=False,
1381 allow_none=False, use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001382 # establish a "logical" server connection
1383
1384 # get the url
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001385 import urllib.parse
1386 type, uri = urllib.parse.splittype(uri)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001387 if type not in ("http", "https"):
Collin Winterce36ad82007-08-30 01:19:48 +00001388 raise IOError("unsupported XML-RPC protocol")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001389 self.__host, self.__handler = urllib.parse.splithost(uri)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001390 if not self.__handler:
1391 self.__handler = "/RPC2"
1392
1393 if transport is None:
1394 if type == "https":
Skip Montanaro174dd222005-05-14 20:54:16 +00001395 transport = SafeTransport(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001396 else:
Skip Montanaro174dd222005-05-14 20:54:16 +00001397 transport = Transport(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001398 self.__transport = transport
1399
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001400 self.__encoding = encoding or 'utf-8'
Fredrik Lundhb9056332001-07-11 17:42:21 +00001401 self.__verbose = verbose
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001402 self.__allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +00001403
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001404 def __close(self):
1405 self.__transport.close()
1406
Fredrik Lundhb9056332001-07-11 17:42:21 +00001407 def __request(self, methodname, params):
1408 # call a method on the remote server
1409
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001410 request = dumps(params, methodname, encoding=self.__encoding,
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001411 allow_none=self.__allow_none).encode(self.__encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001412
1413 response = self.__transport.request(
1414 self.__host,
1415 self.__handler,
1416 request,
1417 verbose=self.__verbose
1418 )
1419
1420 if len(response) == 1:
1421 response = response[0]
1422
1423 return response
1424
1425 def __repr__(self):
1426 return (
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001427 "<ServerProxy for %s%s>" %
Fredrik Lundhb9056332001-07-11 17:42:21 +00001428 (self.__host, self.__handler)
1429 )
1430
1431 __str__ = __repr__
Raymond Hettingercc523fc2003-11-02 09:47:05 +00001432
Fredrik Lundhb9056332001-07-11 17:42:21 +00001433 def __getattr__(self, name):
1434 # magic method dispatcher
1435 return _Method(self.__request, name)
1436
1437 # note: to call a remote object with an non-standard name, use
1438 # result getattr(server, "strange-python-name")(args)
1439
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001440 def __call__(self, attr):
1441 """A workaround to get special attributes on the ServerProxy
1442 without interfering with the magic __getattr__
1443 """
1444 if attr == "close":
1445 return self.__close
1446 elif attr == "transport":
1447 return self.__transport
1448 raise AttributeError("Attribute %r not found" % (attr,))
1449
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001450# compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001451
Fredrik Lundhb9056332001-07-11 17:42:21 +00001452Server = ServerProxy
1453
1454# --------------------------------------------------------------------
1455# test code
1456
1457if __name__ == "__main__":
1458
1459 # simple test program (from the XML-RPC specification)
1460
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001461 # server = ServerProxy("http://localhost:8000") # local server
Martin v. Löwis12237b32004-08-22 16:04:50 +00001462 server = ServerProxy("http://time.xmlrpc.com/RPC2")
Fredrik Lundhb9056332001-07-11 17:42:21 +00001463
Fredrik Lundhb9056332001-07-11 17:42:21 +00001464 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001465 print(server.currentTime.getCurrentTime())
Guido van Rossumb940e112007-01-10 16:19:56 +00001466 except Error as v:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001467 print("ERROR", v)
Martin v. Löwis12237b32004-08-22 16:04:50 +00001468
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001469 # The server at xmlrpc.com doesn't seem to support multicall anymore.
Martin v. Löwis12237b32004-08-22 16:04:50 +00001470 multi = MultiCall(server)
1471 multi.currentTime.getCurrentTime()
1472 multi.currentTime.getCurrentTime()
1473 try:
1474 for response in multi():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001475 print(response)
Guido van Rossumb940e112007-01-10 16:19:56 +00001476 except Error as v:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001477 print("ERROR", v)