blob: 19d4d6986fc3ffca4654b7a7e287a8b2ad217757 [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
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000538 def dump_int(self, value, write):
Skip Montanaro5449e082001-10-17 22:53:33 +0000539 # in case ints are > 32 bits
540 if value > MAXINT or value < MININT:
Collin Winterce36ad82007-08-30 01:19:48 +0000541 raise OverflowError("int exceeds XML-RPC limits")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000542 write("<value><int>")
543 write(str(value))
544 write("</int></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000545 #dispatch[int] = dump_int
Fredrik Lundhb9056332001-07-11 17:42:21 +0000546
Georg Brandl38eceaa2008-05-26 11:14:17 +0000547 def dump_bool(self, value, write):
548 write("<value><boolean>")
549 write(value and "1" or "0")
550 write("</boolean></value>\n")
551 dispatch[bool] = dump_bool
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000552
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000553 def dump_long(self, value, write):
Skip Montanaro5449e082001-10-17 22:53:33 +0000554 if value > MAXINT or value < MININT:
Collin Winterce36ad82007-08-30 01:19:48 +0000555 raise OverflowError("long int exceeds XML-RPC limits")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000556 write("<value><int>")
557 write(str(int(value)))
558 write("</int></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000559 dispatch[int] = dump_long
Skip Montanaro5e9c71b2001-10-10 15:56:34 +0000560
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000561 def dump_double(self, value, write):
562 write("<value><double>")
563 write(repr(value))
564 write("</double></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000565 dispatch[float] = dump_double
Fredrik Lundhb9056332001-07-11 17:42:21 +0000566
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000567 def dump_string(self, value, write, escape=escape):
568 write("<value><string>")
569 write(escape(value))
570 write("</string></value>\n")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000571 dispatch[bytes] = dump_string
Fredrik Lundhb9056332001-07-11 17:42:21 +0000572
Guido van Rossum54ad5232007-05-27 09:17:48 +0000573 def dump_unicode(self, value, write, escape=escape):
Guido van Rossum54ad5232007-05-27 09:17:48 +0000574 write("<value><string>")
575 write(escape(value))
576 write("</string></value>\n")
577 dispatch[str] = dump_unicode
Fredrik Lundhb9056332001-07-11 17:42:21 +0000578
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000579 def dump_array(self, value, write):
580 i = id(value)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000581 if i in self.memo:
Collin Winterce36ad82007-08-30 01:19:48 +0000582 raise TypeError("cannot marshal recursive sequences")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000583 self.memo[i] = None
Fredrik Lundh1538c232001-10-01 19:42:03 +0000584 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000585 write("<value><array><data>\n")
586 for v in value:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000587 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000588 write("</data></array></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000589 del self.memo[i]
Guido van Rossum13257902007-06-07 23:15:56 +0000590 dispatch[tuple] = dump_array
591 dispatch[list] = dump_array
Fredrik Lundhb9056332001-07-11 17:42:21 +0000592
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000593 def dump_struct(self, value, write, escape=escape):
594 i = id(value)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000595 if i in self.memo:
Collin Winterce36ad82007-08-30 01:19:48 +0000596 raise TypeError("cannot marshal recursive dictionaries")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000597 self.memo[i] = None
Fredrik Lundh1538c232001-10-01 19:42:03 +0000598 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000599 write("<value><struct>\n")
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000600 for k, v in value.items():
Fredrik Lundhb9056332001-07-11 17:42:21 +0000601 write("<member>\n")
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000602 if not isinstance(k, str):
Collin Winterce36ad82007-08-30 01:19:48 +0000603 raise TypeError("dictionary key must be string")
Fredrik Lundh1538c232001-10-01 19:42:03 +0000604 write("<name>%s</name>\n" % escape(k))
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000605 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000606 write("</member>\n")
607 write("</struct></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000608 del self.memo[i]
Guido van Rossum13257902007-06-07 23:15:56 +0000609 dispatch[dict] = dump_struct
Fredrik Lundhb9056332001-07-11 17:42:21 +0000610
Fred Drakeba613c32005-02-10 18:33:30 +0000611 if datetime:
612 def dump_datetime(self, value, write):
613 write("<value><dateTime.iso8601>")
Christian Heimesdae2a892008-04-19 00:55:37 +0000614 write(_strftime(value))
Fred Drakeba613c32005-02-10 18:33:30 +0000615 write("</dateTime.iso8601></value>\n")
616 dispatch[datetime.datetime] = dump_datetime
617
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000618 def dump_instance(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000619 # check for special wrappers
620 if value.__class__ in WRAPPERS:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000621 self.write = write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000622 value.encode(self)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000623 del self.write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000624 else:
625 # store instance attributes as a struct (really?)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000626 self.dump_struct(value.__dict__, write)
Guido van Rossume4dea982006-04-21 13:45:00 +0000627 dispatch[DateTime] = dump_instance
628 dispatch[Binary] = dump_instance
Thomas Wouters89f507f2006-12-13 04:49:30 +0000629 # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
630 # for the p3yk merge, this should probably be fixed more neatly.
631 dispatch["_arbitrary_instance"] = dump_instance
Fredrik Lundhb9056332001-07-11 17:42:21 +0000632
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000633##
634# XML-RPC unmarshaller.
635#
636# @see loads
637
Fredrik Lundhb9056332001-07-11 17:42:21 +0000638class Unmarshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000639 """Unmarshal an XML-RPC response, based on incoming XML event
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000640 messages (start, data, end). Call close() to get the resulting
Fred Drake1b410792001-09-04 18:55:03 +0000641 data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000642
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000643 Note that this reader is fairly tolerant, and gladly accepts bogus
644 XML-RPC data without complaining (but not bogus XML).
Fred Drake1b410792001-09-04 18:55:03 +0000645 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000646
647 # and again, if you don't understand what's going on in here,
648 # that's perfectly ok.
649
Georg Brandlfe991052009-09-16 15:54:04 +0000650 def __init__(self, use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000651 self._type = None
652 self._stack = []
653 self._marks = []
654 self._data = []
655 self._methodname = None
656 self._encoding = "utf-8"
657 self.append = self._stack.append
Skip Montanaro174dd222005-05-14 20:54:16 +0000658 self._use_datetime = use_datetime
659 if use_datetime and not datetime:
Collin Winterce36ad82007-08-30 01:19:48 +0000660 raise ValueError("the datetime module is not available")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000661
662 def close(self):
663 # return response tuple and target method
664 if self._type is None or self._marks:
665 raise ResponseError()
666 if self._type == "fault":
Guido van Rossum68468eb2003-02-27 20:14:51 +0000667 raise Fault(**self._stack[0])
Fredrik Lundhb9056332001-07-11 17:42:21 +0000668 return tuple(self._stack)
669
670 def getmethodname(self):
671 return self._methodname
672
673 #
674 # event handlers
675
676 def xml(self, encoding, standalone):
677 self._encoding = encoding
678 # FIXME: assert standalone == 1 ???
679
680 def start(self, tag, attrs):
681 # prepare to handle this element
682 if tag == "array" or tag == "struct":
683 self._marks.append(len(self._stack))
684 self._data = []
685 self._value = (tag == "value")
686
687 def data(self, text):
688 self._data.append(text)
689
Neal Norwitzff113342007-04-17 08:42:15 +0000690 def end(self, tag):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000691 # call the appropriate end tag handler
692 try:
693 f = self.dispatch[tag]
694 except KeyError:
695 pass # unknown tag ?
696 else:
Neal Norwitzff113342007-04-17 08:42:15 +0000697 return f(self, "".join(self._data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000698
699 #
700 # accelerator support
701
702 def end_dispatch(self, tag, data):
703 # dispatch data
704 try:
705 f = self.dispatch[tag]
706 except KeyError:
707 pass # unknown tag ?
708 else:
709 return f(self, data)
710
711 #
712 # element decoders
713
714 dispatch = {}
715
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000716 def end_nil (self, data):
717 self.append(None)
718 self._value = 0
719 dispatch["nil"] = end_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000720
Fredrik Lundh1538c232001-10-01 19:42:03 +0000721 def end_boolean(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000722 if data == "0":
723 self.append(False)
724 elif data == "1":
725 self.append(True)
726 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000727 raise TypeError("bad boolean value")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000728 self._value = 0
729 dispatch["boolean"] = end_boolean
730
Fredrik Lundh1538c232001-10-01 19:42:03 +0000731 def end_int(self, data):
732 self.append(int(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000733 self._value = 0
734 dispatch["i4"] = end_int
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000735 dispatch["i8"] = end_int
Fredrik Lundhb9056332001-07-11 17:42:21 +0000736 dispatch["int"] = end_int
737
Fredrik Lundh1538c232001-10-01 19:42:03 +0000738 def end_double(self, data):
739 self.append(float(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000740 self._value = 0
741 dispatch["double"] = end_double
742
Fredrik Lundh1538c232001-10-01 19:42:03 +0000743 def end_string(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000744 if self._encoding:
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000745 data = data.decode(self._encoding)
746 self.append(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000747 self._value = 0
748 dispatch["string"] = end_string
749 dispatch["name"] = end_string # struct keys are always strings
750
751 def end_array(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000752 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000753 # map arrays to Python lists
754 self._stack[mark:] = [self._stack[mark:]]
755 self._value = 0
756 dispatch["array"] = end_array
757
758 def end_struct(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000759 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000760 # map structs to Python dictionaries
761 dict = {}
762 items = self._stack[mark:]
763 for i in range(0, len(items), 2):
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000764 dict[items[i]] = items[i+1]
Fredrik Lundhb9056332001-07-11 17:42:21 +0000765 self._stack[mark:] = [dict]
766 self._value = 0
767 dispatch["struct"] = end_struct
768
Fredrik Lundh1538c232001-10-01 19:42:03 +0000769 def end_base64(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000770 value = Binary()
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000771 value.decode(data.encode("ascii"))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000772 self.append(value)
773 self._value = 0
774 dispatch["base64"] = end_base64
775
Fredrik Lundh1538c232001-10-01 19:42:03 +0000776 def end_dateTime(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000777 value = DateTime()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000778 value.decode(data)
Skip Montanaro174dd222005-05-14 20:54:16 +0000779 if self._use_datetime:
780 value = _datetime_type(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000781 self.append(value)
782 dispatch["dateTime.iso8601"] = end_dateTime
783
784 def end_value(self, data):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000785 # if we stumble upon a value element with no internal
Fredrik Lundhb9056332001-07-11 17:42:21 +0000786 # elements, treat it as a string element
787 if self._value:
788 self.end_string(data)
789 dispatch["value"] = end_value
790
791 def end_params(self, data):
792 self._type = "params"
793 dispatch["params"] = end_params
794
795 def end_fault(self, data):
796 self._type = "fault"
797 dispatch["fault"] = end_fault
798
Fredrik Lundh1538c232001-10-01 19:42:03 +0000799 def end_methodName(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000800 if self._encoding:
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000801 data = data.decode(self._encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000802 self._methodname = data
803 self._type = "methodName" # no params
804 dispatch["methodName"] = end_methodName
805
Martin v. Löwis45394c22003-10-31 13:49:36 +0000806## Multicall support
807#
Fredrik Lundhb9056332001-07-11 17:42:21 +0000808
Martin v. Löwis45394c22003-10-31 13:49:36 +0000809class _MultiCallMethod:
810 # some lesser magic to store calls made to a MultiCall object
811 # for batch execution
812 def __init__(self, call_list, name):
813 self.__call_list = call_list
814 self.__name = name
815 def __getattr__(self, name):
816 return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
817 def __call__(self, *args):
818 self.__call_list.append((self.__name, args))
819
Martin v. Löwis12237b32004-08-22 16:04:50 +0000820class MultiCallIterator:
Martin v. Löwis45394c22003-10-31 13:49:36 +0000821 """Iterates over the results of a multicall. Exceptions are
822 thrown in response to xmlrpc faults."""
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000823
Martin v. Löwis12237b32004-08-22 16:04:50 +0000824 def __init__(self, results):
825 self.results = results
826
827 def __getitem__(self, i):
828 item = self.results[i]
829 if type(item) == type({}):
830 raise Fault(item['faultCode'], item['faultString'])
831 elif type(item) == type([]):
832 return item[0]
Martin v. Löwis45394c22003-10-31 13:49:36 +0000833 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000834 raise ValueError("unexpected type in multicall result")
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000835
Martin v. Löwis45394c22003-10-31 13:49:36 +0000836class MultiCall:
837 """server -> a object used to boxcar method calls
838
839 server should be a ServerProxy object.
840
841 Methods can be added to the MultiCall using normal
842 method call syntax e.g.:
843
844 multicall = MultiCall(server_proxy)
845 multicall.add(2,3)
846 multicall.get_address("Guido")
847
848 To execute the multicall, call the MultiCall object e.g.:
849
850 add_result, address = multicall()
851 """
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000852
Martin v. Löwis45394c22003-10-31 13:49:36 +0000853 def __init__(self, server):
854 self.__server = server
855 self.__call_list = []
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000856
Martin v. Löwis45394c22003-10-31 13:49:36 +0000857 def __repr__(self):
858 return "<MultiCall at %x>" % id(self)
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000859
Martin v. Löwis45394c22003-10-31 13:49:36 +0000860 __str__ = __repr__
861
862 def __getattr__(self, name):
863 return _MultiCallMethod(self.__call_list, name)
864
865 def __call__(self):
866 marshalled_list = []
867 for name, args in self.__call_list:
868 marshalled_list.append({'methodName' : name, 'params' : args})
869
870 return MultiCallIterator(self.__server.system.multicall(marshalled_list))
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000871
Fredrik Lundhb9056332001-07-11 17:42:21 +0000872# --------------------------------------------------------------------
873# convenience functions
874
Georg Brandl38eceaa2008-05-26 11:14:17 +0000875FastMarshaller = FastParser = FastUnmarshaller = None
876
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000877##
878# Create a parser object, and connect it to an unmarshalling instance.
879# This function picks the fastest available XML parser.
880#
881# return A (parser, unmarshaller) tuple.
882
Georg Brandlfe991052009-09-16 15:54:04 +0000883def getparser(use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000884 """getparser() -> parser, unmarshaller
885
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000886 Create an instance of the fastest available parser, and attach it
887 to an unmarshalling object. Return both objects.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000888 """
Skip Montanaro174dd222005-05-14 20:54:16 +0000889 if use_datetime and not datetime:
Collin Winterce36ad82007-08-30 01:19:48 +0000890 raise ValueError("the datetime module is not available")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000891 if FastParser and FastUnmarshaller:
Skip Montanaro174dd222005-05-14 20:54:16 +0000892 if use_datetime:
893 mkdatetime = _datetime_type
894 else:
895 mkdatetime = _datetime
896 target = FastUnmarshaller(True, False, _binary, mkdatetime, Fault)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000897 parser = FastParser(target)
898 else:
Skip Montanaro174dd222005-05-14 20:54:16 +0000899 target = Unmarshaller(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000900 if FastParser:
901 parser = FastParser(target)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000902 else:
Georg Brandlcef803f2009-06-04 09:04:53 +0000903 parser = ExpatParser(target)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000904 return parser, target
905
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000906##
907# Convert a Python tuple or a Fault instance to an XML-RPC packet.
908#
909# @def dumps(params, **options)
910# @param params A tuple or Fault instance.
911# @keyparam methodname If given, create a methodCall request for
912# this method name.
913# @keyparam methodresponse If given, create a methodResponse packet.
914# If used with a tuple, the tuple must be a singleton (that is,
915# it must contain exactly one element).
916# @keyparam encoding The packet encoding.
917# @return A string containing marshalled data.
918
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000919def dumps(params, methodname=None, methodresponse=None, encoding=None,
Georg Brandlfe991052009-09-16 15:54:04 +0000920 allow_none=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000921 """data [,options] -> marshalled data
922
923 Convert an argument tuple or a Fault instance to an XML-RPC
924 request (or response, if the methodresponse option is used).
925
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000926 In addition to the data object, the following options can be given
927 as keyword arguments:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000928
929 methodname: the method name for a methodCall packet
930
931 methodresponse: true to create a methodResponse packet.
932 If this option is used with a tuple, the tuple must be
933 a singleton (i.e. it can contain only one element).
934
935 encoding: the packet encoding (default is UTF-8)
936
937 All 8-bit strings in the data structure are assumed to use the
938 packet encoding. Unicode strings are automatically converted,
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000939 where necessary.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000940 """
941
Guido van Rossum13257902007-06-07 23:15:56 +0000942 assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
Fredrik Lundhb9056332001-07-11 17:42:21 +0000943 if isinstance(params, Fault):
944 methodresponse = 1
Guido van Rossum13257902007-06-07 23:15:56 +0000945 elif methodresponse and isinstance(params, tuple):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000946 assert len(params) == 1, "response tuple must be a singleton"
947
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000948 if not encoding:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000949 encoding = "utf-8"
950
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000951 if FastMarshaller:
952 m = FastMarshaller(encoding)
953 else:
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000954 m = Marshaller(encoding, allow_none)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000955
Fredrik Lundhb9056332001-07-11 17:42:21 +0000956 data = m.dumps(params)
957
958 if encoding != "utf-8":
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000959 xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000960 else:
961 xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
962
963 # standard XML-RPC wrappings
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000964 if methodname:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000965 # a method call
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000966 if not isinstance(methodname, str):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000967 methodname = methodname.encode(encoding)
968 data = (
969 xmlheader,
970 "<methodCall>\n"
971 "<methodName>", methodname, "</methodName>\n",
972 data,
973 "</methodCall>\n"
974 )
975 elif methodresponse:
976 # a method response, or a fault structure
977 data = (
978 xmlheader,
979 "<methodResponse>\n",
980 data,
981 "</methodResponse>\n"
982 )
983 else:
984 return data # return as is
Neal Norwitzff113342007-04-17 08:42:15 +0000985 return "".join(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000986
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000987##
988# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
989# represents a fault condition, this function raises a Fault exception.
990#
991# @param data An XML-RPC packet, given as an 8-bit string.
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000992# @return A tuple containing the unpacked data, and the method name
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000993# (None if not present).
994# @see Fault
995
Georg Brandlfe991052009-09-16 15:54:04 +0000996def loads(data, use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000997 """data -> unmarshalled data, method name
998
999 Convert an XML-RPC packet to unmarshalled data plus a method
1000 name (None if not present).
1001
1002 If the XML-RPC packet represents a fault condition, this function
1003 raises a Fault exception.
1004 """
Skip Montanaro174dd222005-05-14 20:54:16 +00001005 p, u = getparser(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001006 p.feed(data)
1007 p.close()
1008 return u.close(), u.getmethodname()
1009
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001010##
1011# Encode a string using the gzip content encoding such as specified by the
1012# Content-Encoding: gzip
1013# in the HTTP header, as described in RFC 1952
1014#
1015# @param data the unencoded data
1016# @return the encoded data
1017
1018def gzip_encode(data):
1019 """data -> gzip encoded data
1020
1021 Encode data using the gzip content encoding as described in RFC 1952
1022 """
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001023 if not gzip:
1024 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001025 f = BytesIO()
1026 gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
1027 gzf.write(data)
1028 gzf.close()
1029 encoded = f.getvalue()
1030 f.close()
1031 return encoded
1032
1033##
1034# Decode a string using the gzip content encoding such as specified by the
1035# Content-Encoding: gzip
1036# in the HTTP header, as described in RFC 1952
1037#
1038# @param data The encoded data
1039# @return the unencoded data
1040# @raises ValueError if data is not correctly coded.
1041
1042def gzip_decode(data):
1043 """gzip encoded data -> unencoded data
1044
1045 Decode data using the gzip content encoding as described in RFC 1952
1046 """
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001047 if not gzip:
1048 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001049 f = BytesIO(data)
1050 gzf = gzip.GzipFile(mode="rb", fileobj=f)
1051 try:
1052 decoded = gzf.read()
1053 except IOError:
1054 raise ValueError("invalid data")
1055 f.close()
1056 gzf.close()
1057 return decoded
1058
1059##
1060# Return a decoded file-like object for the gzip encoding
1061# as described in RFC 1952.
1062#
1063# @param response A stream supporting a read() method
1064# @return a file-like object that the decoded data can be read() from
1065
Kristján Valur Jónsson9ab07312009-07-19 22:38:38 +00001066class GzipDecodedResponse(gzip.GzipFile if gzip else object):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001067 """a file-like object to decode a response encoded with the gzip
1068 method, as described in RFC 1952.
1069 """
1070 def __init__(self, response):
1071 #response doesn't support tell() and read(), required by
1072 #GzipFile
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001073 if not gzip:
1074 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001075 self.io = BytesIO(response.read())
1076 gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io)
1077
1078 def close(self):
1079 gzip.GzipFile.close(self)
1080 self.io.close()
1081
Fredrik Lundhb9056332001-07-11 17:42:21 +00001082
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
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001109 #if true, we'll request gzip encoding
1110 accept_gzip_encoding = True
1111
1112 # if positive, encode request using gzip if it exceeds this threshold
1113 # note that many server will get confused, so only use it if you know
1114 # that they can decode such a request
1115 encode_threshold = None #None = don't encode
1116
Georg Brandlfe991052009-09-16 15:54:04 +00001117 def __init__(self, use_datetime=False):
Skip Montanaro174dd222005-05-14 20:54:16 +00001118 self._use_datetime = use_datetime
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001119 self._connection = (None, None)
1120 self._extra_headers = []
Skip Montanaro174dd222005-05-14 20:54:16 +00001121
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001122 ##
1123 # Send a complete request, and parse the response.
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001124 # Retry request if a cached connection has disconnected.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001125 #
1126 # @param host Target host.
1127 # @param handler Target PRC handler.
1128 # @param request_body XML-RPC request body.
1129 # @param verbose Debugging flag.
1130 # @return Parsed response.
1131
Georg Brandlfe991052009-09-16 15:54:04 +00001132 def request(self, host, handler, request_body, verbose=False):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001133 #retry request once if cached connection has gone cold
1134 for i in (0, 1):
1135 try:
1136 return self.single_request(host, handler, request_body, verbose)
Kristján Valur Jónsson43535d92009-07-03 23:23:50 +00001137 except socket.error as e:
Victor Stinner756f5472010-07-24 02:24:55 +00001138 if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
Kristján Valur Jónsson43535d92009-07-03 23:23:50 +00001139 raise
1140 except http.client.BadStatusLine: #close after we sent request
1141 if i:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001142 raise
1143
Georg Brandlfe991052009-09-16 15:54:04 +00001144 def single_request(self, host, handler, request_body, verbose=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001145 # issue XML-RPC request
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001146 try:
1147 http_conn = self.send_request(host, handler, request_body, verbose)
1148 resp = http_conn.getresponse()
1149 if resp.status == 200:
1150 self.verbose = verbose
1151 return self.parse_response(resp)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001152
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001153 except Fault:
1154 raise
1155 except Exception:
1156 #All unexpected errors leave connection in
1157 # a strange state, so we clear it.
1158 self.close()
1159 raise
Fredrik Lundhb9056332001-07-11 17:42:21 +00001160
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001161 #We got an error response.
1162 #Discard any response data and raise exception
1163 if resp.getheader("content-length", ""):
1164 resp.read()
1165 raise ProtocolError(
1166 host + handler,
1167 resp.status, resp.reason,
1168 dict(resp.getheaders())
1169 )
Fredrik Lundhb9056332001-07-11 17:42:21 +00001170
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001171
1172 ##
1173 # Create parser.
1174 #
1175 # @return A 2-tuple containing a parser and a unmarshaller.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001176
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001177 def getparser(self):
1178 # get parser and unmarshaller
Skip Montanaro174dd222005-05-14 20:54:16 +00001179 return getparser(use_datetime=self._use_datetime)
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001180
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001181 ##
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001182 # Get authorization info from host parameter
1183 # Host may be a string, or a (host, x509-dict) tuple; if a string,
1184 # it is checked for a "user:pw@host" format, and a "Basic
1185 # Authentication" header is added if appropriate.
1186 #
1187 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1188 # @return A 3-tuple containing (actual host, extra headers,
1189 # x509 info). The header and x509 fields may be None.
1190
1191 def get_host_info(self, host):
1192
1193 x509 = {}
Guido van Rossum13257902007-06-07 23:15:56 +00001194 if isinstance(host, tuple):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001195 host, x509 = host
1196
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001197 import urllib.parse
1198 auth, host = urllib.parse.splituser(host)
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001199
1200 if auth:
1201 import base64
Georg Brandlc8dcfb62009-02-13 10:50:01 +00001202 auth = urllib.parse.unquote_to_bytes(auth)
Georg Brandlb54d8012009-06-04 09:11:51 +00001203 auth = base64.encodebytes(auth).decode("utf-8")
Neal Norwitzff113342007-04-17 08:42:15 +00001204 auth = "".join(auth.split()) # get rid of whitespace
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001205 extra_headers = [
1206 ("Authorization", "Basic " + auth)
1207 ]
1208 else:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001209 extra_headers = []
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001210
1211 return host, extra_headers, x509
1212
1213 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001214 # Connect to server.
1215 #
1216 # @param host Target host.
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001217 # @return An HTTPConnection object
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001218
Fredrik Lundhb9056332001-07-11 17:42:21 +00001219 def make_connection(self, host):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001220 #return an existing connection if possible. This allows
1221 #HTTP/1.1 keep-alive.
1222 if self._connection and host == self._connection[0]:
1223 return self._connection[1]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001224 # create a HTTP connection object from a host descriptor
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001225 chost, self._extra_headers, x509 = self.get_host_info(host)
1226 self._connection = host, http.client.HTTPConnection(chost)
1227 return self._connection[1]
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001228
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001229 ##
1230 # Clear any cached connection object.
1231 # Used in the event of socket errors.
1232 #
1233 def close(self):
1234 if self._connection[1]:
1235 self._connection[1].close()
1236 self._connection = (None, None)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001237
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001238 ##
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001239 # Send HTTP request.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001240 #
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001241 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1242 # @param handler Targer RPC handler (a path relative to host)
1243 # @param request_body The XML-RPC request body
1244 # @param debug Enable debugging if debug is true.
1245 # @return An HTTPConnection.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001246
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001247 def send_request(self, host, handler, request_body, debug):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001248 connection = self.make_connection(host)
1249 headers = self._extra_headers[:]
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001250 if debug:
1251 connection.set_debuglevel(1)
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001252 if self.accept_gzip_encoding and gzip:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001253 connection.putrequest("POST", handler, skip_accept_encoding=True)
1254 headers.append(("Accept-Encoding", "gzip"))
1255 else:
1256 connection.putrequest("POST", handler)
1257 headers.append(("Content-Type", "text/xml"))
1258 headers.append(("User-Agent", self.user_agent))
1259 self.send_headers(connection, headers)
1260 self.send_content(connection, request_body)
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001261 return connection
Fredrik Lundhb9056332001-07-11 17:42:21 +00001262
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001263 ##
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001264 # Send request headers.
1265 # This function provides a useful hook for subclassing
1266 #
1267 # @param connection httpConnection.
1268 # @param headers list of key,value pairs for HTTP headers
1269
1270 def send_headers(self, connection, headers):
1271 for key, val in headers:
1272 connection.putheader(key, val)
1273
1274 ##
1275 # Send request body.
1276 # This function provides a useful hook for subclassing
1277 #
1278 # @param connection httpConnection.
1279 # @param request_body XML-RPC request body.
1280
1281 def send_content(self, connection, request_body):
1282 #optionally encode the request
1283 if (self.encode_threshold is not None and
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001284 self.encode_threshold < len(request_body) and
1285 gzip):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001286 connection.putheader("Content-Encoding", "gzip")
1287 request_body = gzip_encode(request_body)
1288
1289 connection.putheader("Content-Length", str(len(request_body)))
1290 connection.endheaders(request_body)
1291
1292 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001293 # Parse response.
1294 #
1295 # @param file Stream.
1296 # @return Response tuple and target method.
1297
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001298 def parse_response(self, response):
1299 # read response data from httpresponse, and parse it
Senthil Kumaranf34445f2010-12-08 08:04:49 +00001300 # Check for new http response object, otherwise it is a file object.
1301 if hasattr(response, 'getheader'):
1302 if response.getheader("Content-Encoding", "") == "gzip":
1303 stream = GzipDecodedResponse(response)
1304 else:
1305 stream = response
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001306 else:
1307 stream = response
Fredrik Lundhb9056332001-07-11 17:42:21 +00001308
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001309 p, u = self.getparser()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001310
1311 while 1:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001312 data = stream.read(1024)
1313 if not data:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001314 break
1315 if self.verbose:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001316 print("body:", repr(data))
1317 p.feed(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001318
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001319 if stream is not response:
1320 stream.close()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001321 p.close()
1322
1323 return u.close()
1324
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001325##
1326# Standard transport class for XML-RPC over HTTPS.
1327
Fredrik Lundhb9056332001-07-11 17:42:21 +00001328class SafeTransport(Transport):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001329 """Handles an HTTPS transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001330
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001331 # FIXME: mostly untested
1332
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001333 def make_connection(self, host):
1334 if self._connection and host == self._connection[0]:
1335 return self._connection[1]
1336
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +00001337 if not hasattr(http.client, "HTTPSConnection"):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001338 raise NotImplementedError(
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001339 "your version of http.client doesn't support HTTPS")
1340 # create a HTTPS connection object from a host descriptor
1341 # host may be a string, or a (host, x509-dict) tuple
1342 chost, self._extra_headers, x509 = self.get_host_info(host)
1343 self._connection = host, http.client.HTTPSConnection(chost,
1344 None, **(x509 or {}))
1345 return self._connection[1]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001346
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001347##
1348# Standard server proxy. This class establishes a virtual connection
1349# to an XML-RPC server.
1350# <p>
1351# This class is available as ServerProxy and Server. New code should
1352# use ServerProxy, to avoid confusion.
1353#
1354# @def ServerProxy(uri, **options)
1355# @param uri The connection point on the server.
1356# @keyparam transport A transport factory, compatible with the
1357# standard transport class.
1358# @keyparam encoding The default encoding used for 8-bit strings
1359# (default is UTF-8).
1360# @keyparam verbose Use a true value to enable debugging output.
1361# (printed to standard output).
1362# @see Transport
1363
Fredrik Lundhb9056332001-07-11 17:42:21 +00001364class ServerProxy:
1365 """uri [,options] -> a logical connection to an XML-RPC server
1366
1367 uri is the connection point on the server, given as
1368 scheme://host/target.
1369
1370 The standard implementation always supports the "http" scheme. If
1371 SSL socket support is available (Python 2.0), it also supports
1372 "https".
1373
1374 If the target part and the slash preceding it are both omitted,
1375 "/RPC2" is assumed.
1376
1377 The following options can be given as keyword arguments:
1378
1379 transport: a transport factory
1380 encoding: the request encoding (default is UTF-8)
1381
1382 All 8-bit strings passed to the server proxy are assumed to use
1383 the given encoding.
1384 """
1385
Georg Brandlfe991052009-09-16 15:54:04 +00001386 def __init__(self, uri, transport=None, encoding=None, verbose=False,
1387 allow_none=False, use_datetime=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001388 # establish a "logical" server connection
1389
1390 # get the url
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001391 import urllib.parse
1392 type, uri = urllib.parse.splittype(uri)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001393 if type not in ("http", "https"):
Collin Winterce36ad82007-08-30 01:19:48 +00001394 raise IOError("unsupported XML-RPC protocol")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001395 self.__host, self.__handler = urllib.parse.splithost(uri)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001396 if not self.__handler:
1397 self.__handler = "/RPC2"
1398
1399 if transport is None:
1400 if type == "https":
Skip Montanaro174dd222005-05-14 20:54:16 +00001401 transport = SafeTransport(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001402 else:
Skip Montanaro174dd222005-05-14 20:54:16 +00001403 transport = Transport(use_datetime=use_datetime)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001404 self.__transport = transport
1405
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001406 self.__encoding = encoding or 'utf-8'
Fredrik Lundhb9056332001-07-11 17:42:21 +00001407 self.__verbose = verbose
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001408 self.__allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +00001409
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001410 def __close(self):
1411 self.__transport.close()
1412
Fredrik Lundhb9056332001-07-11 17:42:21 +00001413 def __request(self, methodname, params):
1414 # call a method on the remote server
1415
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001416 request = dumps(params, methodname, encoding=self.__encoding,
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001417 allow_none=self.__allow_none).encode(self.__encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001418
1419 response = self.__transport.request(
1420 self.__host,
1421 self.__handler,
1422 request,
1423 verbose=self.__verbose
1424 )
1425
1426 if len(response) == 1:
1427 response = response[0]
1428
1429 return response
1430
1431 def __repr__(self):
1432 return (
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001433 "<ServerProxy for %s%s>" %
Fredrik Lundhb9056332001-07-11 17:42:21 +00001434 (self.__host, self.__handler)
1435 )
1436
1437 __str__ = __repr__
Raymond Hettingercc523fc2003-11-02 09:47:05 +00001438
Fredrik Lundhb9056332001-07-11 17:42:21 +00001439 def __getattr__(self, name):
1440 # magic method dispatcher
1441 return _Method(self.__request, name)
1442
1443 # note: to call a remote object with an non-standard name, use
1444 # result getattr(server, "strange-python-name")(args)
1445
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001446 def __call__(self, attr):
1447 """A workaround to get special attributes on the ServerProxy
1448 without interfering with the magic __getattr__
1449 """
1450 if attr == "close":
1451 return self.__close
1452 elif attr == "transport":
1453 return self.__transport
1454 raise AttributeError("Attribute %r not found" % (attr,))
1455
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001456# compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001457
Fredrik Lundhb9056332001-07-11 17:42:21 +00001458Server = ServerProxy
1459
1460# --------------------------------------------------------------------
1461# test code
1462
1463if __name__ == "__main__":
1464
1465 # simple test program (from the XML-RPC specification)
1466
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001467 # server = ServerProxy("http://localhost:8000") # local server
Martin v. Löwis12237b32004-08-22 16:04:50 +00001468 server = ServerProxy("http://time.xmlrpc.com/RPC2")
Fredrik Lundhb9056332001-07-11 17:42:21 +00001469
Fredrik Lundhb9056332001-07-11 17:42:21 +00001470 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001471 print(server.currentTime.getCurrentTime())
Guido van Rossumb940e112007-01-10 16:19:56 +00001472 except Error as v:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001473 print("ERROR", v)
Martin v. Löwis12237b32004-08-22 16:04:50 +00001474
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001475 # The server at xmlrpc.com doesn't seem to support multicall anymore.
Martin v. Löwis12237b32004-08-22 16:04:50 +00001476 multi = MultiCall(server)
1477 multi.currentTime.getCurrentTime()
1478 multi.currentTime.getCurrentTime()
1479 try:
1480 for response in multi():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001481 print(response)
Guido van Rossumb940e112007-01-10 16:19:56 +00001482 except Error as v:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001483 print("ERROR", v)