logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

client.py (49309B)


  1. #
  2. # XML-RPC CLIENT LIBRARY
  3. # $Id$
  4. #
  5. # an XML-RPC client interface for Python.
  6. #
  7. # the marshalling and response parser code can also be used to
  8. # implement XML-RPC servers.
  9. #
  10. # Notes:
  11. # this version is designed to work with Python 2.1 or newer.
  12. #
  13. # 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)
  27. # 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)
  29. # 2001-09-03 fl Allow Transport subclass to override getparser
  30. # 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
  31. # 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)
  33. # 2001-10-02 fl More dumps microtuning
  34. # 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
  35. # 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
  36. # 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
  37. # 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
  38. # 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
  43. # 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
  44. # 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
  50. # 2003-10-31 mvl Add multicall support
  51. # 2004-08-20 mvl Bump minimum supported Python version to 2.1
  52. # 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
  53. #
  54. # Copyright (c) 1999-2002 by Secret Labs AB.
  55. # Copyright (c) 1999-2002 by Fredrik Lundh.
  56. #
  57. # info@pythonware.com
  58. # http://www.pythonware.com
  59. #
  60. # --------------------------------------------------------------------
  61. # The XML-RPC client interface is
  62. #
  63. # Copyright (c) 1999-2002 by Secret Labs AB
  64. # Copyright (c) 1999-2002 by Fredrik Lundh
  65. #
  66. # By obtaining, using, and/or copying this software and/or its
  67. # associated documentation, you agree that you have read, understood,
  68. # and will comply with the following terms and conditions:
  69. #
  70. # Permission to use, copy, modify, and distribute this software and
  71. # its associated documentation for any purpose and without fee is
  72. # hereby granted, provided that the above copyright notice appears in
  73. # all copies, and that both that copyright notice and this permission
  74. # notice appear in supporting documentation, and that the name of
  75. # Secret Labs AB or the author not be used in advertising or publicity
  76. # pertaining to distribution of the software without specific, written
  77. # prior permission.
  78. #
  79. # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  80. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  81. # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
  82. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  83. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  84. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  85. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  86. # OF THIS SOFTWARE.
  87. # --------------------------------------------------------------------
  88. """
  89. An XML-RPC client interface for Python.
  90. The marshalling and response parser code can also be used to
  91. implement XML-RPC servers.
  92. Exported exceptions:
  93. Error Base class for client errors
  94. ProtocolError Indicates an HTTP protocol error
  95. ResponseError Indicates a broken response package
  96. Fault Indicates an XML-RPC fault package
  97. Exported classes:
  98. ServerProxy Represents a logical connection to an XML-RPC server
  99. MultiCall Executor of boxcared xmlrpc requests
  100. DateTime dateTime wrapper for an ISO 8601 string or time tuple or
  101. localtime integer value to generate a "dateTime.iso8601"
  102. XML-RPC value
  103. Binary binary data wrapper
  104. Marshaller Generate an XML-RPC params chunk from a Python data structure
  105. Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
  106. Transport Handles an HTTP transaction to an XML-RPC server
  107. SafeTransport Handles an HTTPS transaction to an XML-RPC server
  108. Exported constants:
  109. (none)
  110. Exported functions:
  111. getparser Create instance of the fastest available parser & attach
  112. to an unmarshalling object
  113. dumps Convert an argument tuple or a Fault instance to an XML-RPC
  114. request (or response, if the methodresponse option is used).
  115. loads Convert an XML-RPC packet to unmarshalled data plus a method
  116. name (None if not present).
  117. """
  118. import base64
  119. import sys
  120. import time
  121. from datetime import datetime
  122. from decimal import Decimal
  123. import http.client
  124. import urllib.parse
  125. from xml.parsers import expat
  126. import errno
  127. from io import BytesIO
  128. try:
  129. import gzip
  130. except ImportError:
  131. gzip = None #python can be built without zlib/gzip support
  132. # --------------------------------------------------------------------
  133. # Internal stuff
  134. def escape(s):
  135. s = s.replace("&", "&amp;")
  136. s = s.replace("<", "&lt;")
  137. return s.replace(">", "&gt;",)
  138. # used in User-Agent header sent
  139. __version__ = '%d.%d' % sys.version_info[:2]
  140. # xmlrpc integer limits
  141. MAXINT = 2**31-1
  142. MININT = -2**31
  143. # --------------------------------------------------------------------
  144. # Error constants (from Dan Libby's specification at
  145. # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
  146. # Ranges of errors
  147. PARSE_ERROR = -32700
  148. SERVER_ERROR = -32600
  149. APPLICATION_ERROR = -32500
  150. SYSTEM_ERROR = -32400
  151. TRANSPORT_ERROR = -32300
  152. # Specific errors
  153. NOT_WELLFORMED_ERROR = -32700
  154. UNSUPPORTED_ENCODING = -32701
  155. INVALID_ENCODING_CHAR = -32702
  156. INVALID_XMLRPC = -32600
  157. METHOD_NOT_FOUND = -32601
  158. INVALID_METHOD_PARAMS = -32602
  159. INTERNAL_ERROR = -32603
  160. # --------------------------------------------------------------------
  161. # Exceptions
  162. ##
  163. # Base class for all kinds of client-side errors.
  164. class Error(Exception):
  165. """Base class for client errors."""
  166. __str__ = object.__str__
  167. ##
  168. # Indicates an HTTP-level protocol error. This is raised by the HTTP
  169. # transport layer, if the server returns an error code other than 200
  170. # (OK).
  171. #
  172. # @param url The target URL.
  173. # @param errcode The HTTP error code.
  174. # @param errmsg The HTTP error message.
  175. # @param headers The HTTP header dictionary.
  176. class ProtocolError(Error):
  177. """Indicates an HTTP protocol error."""
  178. def __init__(self, url, errcode, errmsg, headers):
  179. Error.__init__(self)
  180. self.url = url
  181. self.errcode = errcode
  182. self.errmsg = errmsg
  183. self.headers = headers
  184. def __repr__(self):
  185. return (
  186. "<%s for %s: %s %s>" %
  187. (self.__class__.__name__, self.url, self.errcode, self.errmsg)
  188. )
  189. ##
  190. # Indicates a broken XML-RPC response package. This exception is
  191. # raised by the unmarshalling layer, if the XML-RPC response is
  192. # malformed.
  193. class ResponseError(Error):
  194. """Indicates a broken response package."""
  195. pass
  196. ##
  197. # Indicates an XML-RPC fault response package. This exception is
  198. # raised by the unmarshalling layer, if the XML-RPC response contains
  199. # a fault string. This exception can also be used as a class, to
  200. # generate a fault XML-RPC message.
  201. #
  202. # @param faultCode The XML-RPC fault code.
  203. # @param faultString The XML-RPC fault string.
  204. class Fault(Error):
  205. """Indicates an XML-RPC fault package."""
  206. def __init__(self, faultCode, faultString, **extra):
  207. Error.__init__(self)
  208. self.faultCode = faultCode
  209. self.faultString = faultString
  210. def __repr__(self):
  211. return "<%s %s: %r>" % (self.__class__.__name__,
  212. self.faultCode, self.faultString)
  213. # --------------------------------------------------------------------
  214. # Special values
  215. ##
  216. # Backwards compatibility
  217. boolean = Boolean = bool
  218. ##
  219. # Wrapper for XML-RPC DateTime values. This converts a time value to
  220. # the format used by XML-RPC.
  221. # <p>
  222. # The value can be given as a datetime object, as a string in the
  223. # format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
  224. # time.localtime()), or an integer value (as returned by time.time()).
  225. # The wrapper uses time.localtime() to convert an integer to a time
  226. # tuple.
  227. #
  228. # @param value The time, given as a datetime object, an ISO 8601 string,
  229. # a time tuple, or an integer time value.
  230. # Issue #13305: different format codes across platforms
  231. _day0 = datetime(1, 1, 1)
  232. if _day0.strftime('%Y') == '0001': # Mac OS X
  233. def _iso8601_format(value):
  234. return value.strftime("%Y%m%dT%H:%M:%S")
  235. elif _day0.strftime('%4Y') == '0001': # Linux
  236. def _iso8601_format(value):
  237. return value.strftime("%4Y%m%dT%H:%M:%S")
  238. else:
  239. def _iso8601_format(value):
  240. return value.strftime("%Y%m%dT%H:%M:%S").zfill(17)
  241. del _day0
  242. def _strftime(value):
  243. if isinstance(value, datetime):
  244. return _iso8601_format(value)
  245. if not isinstance(value, (tuple, time.struct_time)):
  246. if value == 0:
  247. value = time.time()
  248. value = time.localtime(value)
  249. return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
  250. class DateTime:
  251. """DateTime wrapper for an ISO 8601 string or time tuple or
  252. localtime integer value to generate 'dateTime.iso8601' XML-RPC
  253. value.
  254. """
  255. def __init__(self, value=0):
  256. if isinstance(value, str):
  257. self.value = value
  258. else:
  259. self.value = _strftime(value)
  260. def make_comparable(self, other):
  261. if isinstance(other, DateTime):
  262. s = self.value
  263. o = other.value
  264. elif isinstance(other, datetime):
  265. s = self.value
  266. o = _iso8601_format(other)
  267. elif isinstance(other, str):
  268. s = self.value
  269. o = other
  270. elif hasattr(other, "timetuple"):
  271. s = self.timetuple()
  272. o = other.timetuple()
  273. else:
  274. s = self
  275. o = NotImplemented
  276. return s, o
  277. def __lt__(self, other):
  278. s, o = self.make_comparable(other)
  279. if o is NotImplemented:
  280. return NotImplemented
  281. return s < o
  282. def __le__(self, other):
  283. s, o = self.make_comparable(other)
  284. if o is NotImplemented:
  285. return NotImplemented
  286. return s <= o
  287. def __gt__(self, other):
  288. s, o = self.make_comparable(other)
  289. if o is NotImplemented:
  290. return NotImplemented
  291. return s > o
  292. def __ge__(self, other):
  293. s, o = self.make_comparable(other)
  294. if o is NotImplemented:
  295. return NotImplemented
  296. return s >= o
  297. def __eq__(self, other):
  298. s, o = self.make_comparable(other)
  299. if o is NotImplemented:
  300. return NotImplemented
  301. return s == o
  302. def timetuple(self):
  303. return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
  304. ##
  305. # Get date/time value.
  306. #
  307. # @return Date/time value, as an ISO 8601 string.
  308. def __str__(self):
  309. return self.value
  310. def __repr__(self):
  311. return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self))
  312. def decode(self, data):
  313. self.value = str(data).strip()
  314. def encode(self, out):
  315. out.write("<value><dateTime.iso8601>")
  316. out.write(self.value)
  317. out.write("</dateTime.iso8601></value>\n")
  318. def _datetime(data):
  319. # decode xml element contents into a DateTime structure.
  320. value = DateTime()
  321. value.decode(data)
  322. return value
  323. def _datetime_type(data):
  324. return datetime.strptime(data, "%Y%m%dT%H:%M:%S")
  325. ##
  326. # Wrapper for binary data. This can be used to transport any kind
  327. # of binary data over XML-RPC, using BASE64 encoding.
  328. #
  329. # @param data An 8-bit string containing arbitrary data.
  330. class Binary:
  331. """Wrapper for binary data."""
  332. def __init__(self, data=None):
  333. if data is None:
  334. data = b""
  335. else:
  336. if not isinstance(data, (bytes, bytearray)):
  337. raise TypeError("expected bytes or bytearray, not %s" %
  338. data.__class__.__name__)
  339. data = bytes(data) # Make a copy of the bytes!
  340. self.data = data
  341. ##
  342. # Get buffer contents.
  343. #
  344. # @return Buffer contents, as an 8-bit string.
  345. def __str__(self):
  346. return str(self.data, "latin-1") # XXX encoding?!
  347. def __eq__(self, other):
  348. if isinstance(other, Binary):
  349. other = other.data
  350. return self.data == other
  351. def decode(self, data):
  352. self.data = base64.decodebytes(data)
  353. def encode(self, out):
  354. out.write("<value><base64>\n")
  355. encoded = base64.encodebytes(self.data)
  356. out.write(encoded.decode('ascii'))
  357. out.write("</base64></value>\n")
  358. def _binary(data):
  359. # decode xml element contents into a Binary structure
  360. value = Binary()
  361. value.decode(data)
  362. return value
  363. WRAPPERS = (DateTime, Binary)
  364. # --------------------------------------------------------------------
  365. # XML parsers
  366. class ExpatParser:
  367. # fast expat parser for Python 2.0 and later.
  368. def __init__(self, target):
  369. self._parser = parser = expat.ParserCreate(None, None)
  370. self._target = target
  371. parser.StartElementHandler = target.start
  372. parser.EndElementHandler = target.end
  373. parser.CharacterDataHandler = target.data
  374. encoding = None
  375. target.xml(encoding, None)
  376. def feed(self, data):
  377. self._parser.Parse(data, False)
  378. def close(self):
  379. try:
  380. parser = self._parser
  381. except AttributeError:
  382. pass
  383. else:
  384. del self._target, self._parser # get rid of circular references
  385. parser.Parse(b"", True) # end of data
  386. # --------------------------------------------------------------------
  387. # XML-RPC marshalling and unmarshalling code
  388. ##
  389. # XML-RPC marshaller.
  390. #
  391. # @param encoding Default encoding for 8-bit strings. The default
  392. # value is None (interpreted as UTF-8).
  393. # @see dumps
  394. class Marshaller:
  395. """Generate an XML-RPC params chunk from a Python data structure.
  396. Create a Marshaller instance for each set of parameters, and use
  397. the "dumps" method to convert your data (represented as a tuple)
  398. to an XML-RPC params chunk. To write a fault response, pass a
  399. Fault instance instead. You may prefer to use the "dumps" module
  400. function for this purpose.
  401. """
  402. # by the way, if you don't understand what's going on in here,
  403. # that's perfectly ok.
  404. def __init__(self, encoding=None, allow_none=False):
  405. self.memo = {}
  406. self.data = None
  407. self.encoding = encoding
  408. self.allow_none = allow_none
  409. dispatch = {}
  410. def dumps(self, values):
  411. out = []
  412. write = out.append
  413. dump = self.__dump
  414. if isinstance(values, Fault):
  415. # fault instance
  416. write("<fault>\n")
  417. dump({'faultCode': values.faultCode,
  418. 'faultString': values.faultString},
  419. write)
  420. write("</fault>\n")
  421. else:
  422. # parameter block
  423. # FIXME: the xml-rpc specification allows us to leave out
  424. # the entire <params> block if there are no parameters.
  425. # however, changing this may break older code (including
  426. # old versions of xmlrpclib.py), so this is better left as
  427. # is for now. See @XMLRPC3 for more information. /F
  428. write("<params>\n")
  429. for v in values:
  430. write("<param>\n")
  431. dump(v, write)
  432. write("</param>\n")
  433. write("</params>\n")
  434. result = "".join(out)
  435. return result
  436. def __dump(self, value, write):
  437. try:
  438. f = self.dispatch[type(value)]
  439. except KeyError:
  440. # check if this object can be marshalled as a structure
  441. if not hasattr(value, '__dict__'):
  442. raise TypeError("cannot marshal %s objects" % type(value))
  443. # check if this class is a sub-class of a basic type,
  444. # because we don't know how to marshal these types
  445. # (e.g. a string sub-class)
  446. for type_ in type(value).__mro__:
  447. if type_ in self.dispatch.keys():
  448. raise TypeError("cannot marshal %s objects" % type(value))
  449. # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
  450. # for the p3yk merge, this should probably be fixed more neatly.
  451. f = self.dispatch["_arbitrary_instance"]
  452. f(self, value, write)
  453. def dump_nil (self, value, write):
  454. if not self.allow_none:
  455. raise TypeError("cannot marshal None unless allow_none is enabled")
  456. write("<value><nil/></value>")
  457. dispatch[type(None)] = dump_nil
  458. def dump_bool(self, value, write):
  459. write("<value><boolean>")
  460. write(value and "1" or "0")
  461. write("</boolean></value>\n")
  462. dispatch[bool] = dump_bool
  463. def dump_long(self, value, write):
  464. if value > MAXINT or value < MININT:
  465. raise OverflowError("int exceeds XML-RPC limits")
  466. write("<value><int>")
  467. write(str(int(value)))
  468. write("</int></value>\n")
  469. dispatch[int] = dump_long
  470. # backward compatible
  471. dump_int = dump_long
  472. def dump_double(self, value, write):
  473. write("<value><double>")
  474. write(repr(value))
  475. write("</double></value>\n")
  476. dispatch[float] = dump_double
  477. def dump_unicode(self, value, write, escape=escape):
  478. write("<value><string>")
  479. write(escape(value))
  480. write("</string></value>\n")
  481. dispatch[str] = dump_unicode
  482. def dump_bytes(self, value, write):
  483. write("<value><base64>\n")
  484. encoded = base64.encodebytes(value)
  485. write(encoded.decode('ascii'))
  486. write("</base64></value>\n")
  487. dispatch[bytes] = dump_bytes
  488. dispatch[bytearray] = dump_bytes
  489. def dump_array(self, value, write):
  490. i = id(value)
  491. if i in self.memo:
  492. raise TypeError("cannot marshal recursive sequences")
  493. self.memo[i] = None
  494. dump = self.__dump
  495. write("<value><array><data>\n")
  496. for v in value:
  497. dump(v, write)
  498. write("</data></array></value>\n")
  499. del self.memo[i]
  500. dispatch[tuple] = dump_array
  501. dispatch[list] = dump_array
  502. def dump_struct(self, value, write, escape=escape):
  503. i = id(value)
  504. if i in self.memo:
  505. raise TypeError("cannot marshal recursive dictionaries")
  506. self.memo[i] = None
  507. dump = self.__dump
  508. write("<value><struct>\n")
  509. for k, v in value.items():
  510. write("<member>\n")
  511. if not isinstance(k, str):
  512. raise TypeError("dictionary key must be string")
  513. write("<name>%s</name>\n" % escape(k))
  514. dump(v, write)
  515. write("</member>\n")
  516. write("</struct></value>\n")
  517. del self.memo[i]
  518. dispatch[dict] = dump_struct
  519. def dump_datetime(self, value, write):
  520. write("<value><dateTime.iso8601>")
  521. write(_strftime(value))
  522. write("</dateTime.iso8601></value>\n")
  523. dispatch[datetime] = dump_datetime
  524. def dump_instance(self, value, write):
  525. # check for special wrappers
  526. if value.__class__ in WRAPPERS:
  527. self.write = write
  528. value.encode(self)
  529. del self.write
  530. else:
  531. # store instance attributes as a struct (really?)
  532. self.dump_struct(value.__dict__, write)
  533. dispatch[DateTime] = dump_instance
  534. dispatch[Binary] = dump_instance
  535. # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
  536. # for the p3yk merge, this should probably be fixed more neatly.
  537. dispatch["_arbitrary_instance"] = dump_instance
  538. ##
  539. # XML-RPC unmarshaller.
  540. #
  541. # @see loads
  542. class Unmarshaller:
  543. """Unmarshal an XML-RPC response, based on incoming XML event
  544. messages (start, data, end). Call close() to get the resulting
  545. data structure.
  546. Note that this reader is fairly tolerant, and gladly accepts bogus
  547. XML-RPC data without complaining (but not bogus XML).
  548. """
  549. # and again, if you don't understand what's going on in here,
  550. # that's perfectly ok.
  551. def __init__(self, use_datetime=False, use_builtin_types=False):
  552. self._type = None
  553. self._stack = []
  554. self._marks = []
  555. self._data = []
  556. self._value = False
  557. self._methodname = None
  558. self._encoding = "utf-8"
  559. self.append = self._stack.append
  560. self._use_datetime = use_builtin_types or use_datetime
  561. self._use_bytes = use_builtin_types
  562. def close(self):
  563. # return response tuple and target method
  564. if self._type is None or self._marks:
  565. raise ResponseError()
  566. if self._type == "fault":
  567. raise Fault(**self._stack[0])
  568. return tuple(self._stack)
  569. def getmethodname(self):
  570. return self._methodname
  571. #
  572. # event handlers
  573. def xml(self, encoding, standalone):
  574. self._encoding = encoding
  575. # FIXME: assert standalone == 1 ???
  576. def start(self, tag, attrs):
  577. # prepare to handle this element
  578. if ':' in tag:
  579. tag = tag.split(':')[-1]
  580. if tag == "array" or tag == "struct":
  581. self._marks.append(len(self._stack))
  582. self._data = []
  583. if self._value and tag not in self.dispatch:
  584. raise ResponseError("unknown tag %r" % tag)
  585. self._value = (tag == "value")
  586. def data(self, text):
  587. self._data.append(text)
  588. def end(self, tag):
  589. # call the appropriate end tag handler
  590. try:
  591. f = self.dispatch[tag]
  592. except KeyError:
  593. if ':' not in tag:
  594. return # unknown tag ?
  595. try:
  596. f = self.dispatch[tag.split(':')[-1]]
  597. except KeyError:
  598. return # unknown tag ?
  599. return f(self, "".join(self._data))
  600. #
  601. # accelerator support
  602. def end_dispatch(self, tag, data):
  603. # dispatch data
  604. try:
  605. f = self.dispatch[tag]
  606. except KeyError:
  607. if ':' not in tag:
  608. return # unknown tag ?
  609. try:
  610. f = self.dispatch[tag.split(':')[-1]]
  611. except KeyError:
  612. return # unknown tag ?
  613. return f(self, data)
  614. #
  615. # element decoders
  616. dispatch = {}
  617. def end_nil (self, data):
  618. self.append(None)
  619. self._value = 0
  620. dispatch["nil"] = end_nil
  621. def end_boolean(self, data):
  622. if data == "0":
  623. self.append(False)
  624. elif data == "1":
  625. self.append(True)
  626. else:
  627. raise TypeError("bad boolean value")
  628. self._value = 0
  629. dispatch["boolean"] = end_boolean
  630. def end_int(self, data):
  631. self.append(int(data))
  632. self._value = 0
  633. dispatch["i1"] = end_int
  634. dispatch["i2"] = end_int
  635. dispatch["i4"] = end_int
  636. dispatch["i8"] = end_int
  637. dispatch["int"] = end_int
  638. dispatch["biginteger"] = end_int
  639. def end_double(self, data):
  640. self.append(float(data))
  641. self._value = 0
  642. dispatch["double"] = end_double
  643. dispatch["float"] = end_double
  644. def end_bigdecimal(self, data):
  645. self.append(Decimal(data))
  646. self._value = 0
  647. dispatch["bigdecimal"] = end_bigdecimal
  648. def end_string(self, data):
  649. if self._encoding:
  650. data = data.decode(self._encoding)
  651. self.append(data)
  652. self._value = 0
  653. dispatch["string"] = end_string
  654. dispatch["name"] = end_string # struct keys are always strings
  655. def end_array(self, data):
  656. mark = self._marks.pop()
  657. # map arrays to Python lists
  658. self._stack[mark:] = [self._stack[mark:]]
  659. self._value = 0
  660. dispatch["array"] = end_array
  661. def end_struct(self, data):
  662. mark = self._marks.pop()
  663. # map structs to Python dictionaries
  664. dict = {}
  665. items = self._stack[mark:]
  666. for i in range(0, len(items), 2):
  667. dict[items[i]] = items[i+1]
  668. self._stack[mark:] = [dict]
  669. self._value = 0
  670. dispatch["struct"] = end_struct
  671. def end_base64(self, data):
  672. value = Binary()
  673. value.decode(data.encode("ascii"))
  674. if self._use_bytes:
  675. value = value.data
  676. self.append(value)
  677. self._value = 0
  678. dispatch["base64"] = end_base64
  679. def end_dateTime(self, data):
  680. value = DateTime()
  681. value.decode(data)
  682. if self._use_datetime:
  683. value = _datetime_type(data)
  684. self.append(value)
  685. dispatch["dateTime.iso8601"] = end_dateTime
  686. def end_value(self, data):
  687. # if we stumble upon a value element with no internal
  688. # elements, treat it as a string element
  689. if self._value:
  690. self.end_string(data)
  691. dispatch["value"] = end_value
  692. def end_params(self, data):
  693. self._type = "params"
  694. dispatch["params"] = end_params
  695. def end_fault(self, data):
  696. self._type = "fault"
  697. dispatch["fault"] = end_fault
  698. def end_methodName(self, data):
  699. if self._encoding:
  700. data = data.decode(self._encoding)
  701. self._methodname = data
  702. self._type = "methodName" # no params
  703. dispatch["methodName"] = end_methodName
  704. ## Multicall support
  705. #
  706. class _MultiCallMethod:
  707. # some lesser magic to store calls made to a MultiCall object
  708. # for batch execution
  709. def __init__(self, call_list, name):
  710. self.__call_list = call_list
  711. self.__name = name
  712. def __getattr__(self, name):
  713. return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
  714. def __call__(self, *args):
  715. self.__call_list.append((self.__name, args))
  716. class MultiCallIterator:
  717. """Iterates over the results of a multicall. Exceptions are
  718. raised in response to xmlrpc faults."""
  719. def __init__(self, results):
  720. self.results = results
  721. def __getitem__(self, i):
  722. item = self.results[i]
  723. if type(item) == type({}):
  724. raise Fault(item['faultCode'], item['faultString'])
  725. elif type(item) == type([]):
  726. return item[0]
  727. else:
  728. raise ValueError("unexpected type in multicall result")
  729. class MultiCall:
  730. """server -> an object used to boxcar method calls
  731. server should be a ServerProxy object.
  732. Methods can be added to the MultiCall using normal
  733. method call syntax e.g.:
  734. multicall = MultiCall(server_proxy)
  735. multicall.add(2,3)
  736. multicall.get_address("Guido")
  737. To execute the multicall, call the MultiCall object e.g.:
  738. add_result, address = multicall()
  739. """
  740. def __init__(self, server):
  741. self.__server = server
  742. self.__call_list = []
  743. def __repr__(self):
  744. return "<%s at %#x>" % (self.__class__.__name__, id(self))
  745. def __getattr__(self, name):
  746. return _MultiCallMethod(self.__call_list, name)
  747. def __call__(self):
  748. marshalled_list = []
  749. for name, args in self.__call_list:
  750. marshalled_list.append({'methodName' : name, 'params' : args})
  751. return MultiCallIterator(self.__server.system.multicall(marshalled_list))
  752. # --------------------------------------------------------------------
  753. # convenience functions
  754. FastMarshaller = FastParser = FastUnmarshaller = None
  755. ##
  756. # Create a parser object, and connect it to an unmarshalling instance.
  757. # This function picks the fastest available XML parser.
  758. #
  759. # return A (parser, unmarshaller) tuple.
  760. def getparser(use_datetime=False, use_builtin_types=False):
  761. """getparser() -> parser, unmarshaller
  762. Create an instance of the fastest available parser, and attach it
  763. to an unmarshalling object. Return both objects.
  764. """
  765. if FastParser and FastUnmarshaller:
  766. if use_builtin_types:
  767. mkdatetime = _datetime_type
  768. mkbytes = base64.decodebytes
  769. elif use_datetime:
  770. mkdatetime = _datetime_type
  771. mkbytes = _binary
  772. else:
  773. mkdatetime = _datetime
  774. mkbytes = _binary
  775. target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
  776. parser = FastParser(target)
  777. else:
  778. target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
  779. if FastParser:
  780. parser = FastParser(target)
  781. else:
  782. parser = ExpatParser(target)
  783. return parser, target
  784. ##
  785. # Convert a Python tuple or a Fault instance to an XML-RPC packet.
  786. #
  787. # @def dumps(params, **options)
  788. # @param params A tuple or Fault instance.
  789. # @keyparam methodname If given, create a methodCall request for
  790. # this method name.
  791. # @keyparam methodresponse If given, create a methodResponse packet.
  792. # If used with a tuple, the tuple must be a singleton (that is,
  793. # it must contain exactly one element).
  794. # @keyparam encoding The packet encoding.
  795. # @return A string containing marshalled data.
  796. def dumps(params, methodname=None, methodresponse=None, encoding=None,
  797. allow_none=False):
  798. """data [,options] -> marshalled data
  799. Convert an argument tuple or a Fault instance to an XML-RPC
  800. request (or response, if the methodresponse option is used).
  801. In addition to the data object, the following options can be given
  802. as keyword arguments:
  803. methodname: the method name for a methodCall packet
  804. methodresponse: true to create a methodResponse packet.
  805. If this option is used with a tuple, the tuple must be
  806. a singleton (i.e. it can contain only one element).
  807. encoding: the packet encoding (default is UTF-8)
  808. All byte strings in the data structure are assumed to use the
  809. packet encoding. Unicode strings are automatically converted,
  810. where necessary.
  811. """
  812. assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
  813. if isinstance(params, Fault):
  814. methodresponse = 1
  815. elif methodresponse and isinstance(params, tuple):
  816. assert len(params) == 1, "response tuple must be a singleton"
  817. if not encoding:
  818. encoding = "utf-8"
  819. if FastMarshaller:
  820. m = FastMarshaller(encoding)
  821. else:
  822. m = Marshaller(encoding, allow_none)
  823. data = m.dumps(params)
  824. if encoding != "utf-8":
  825. xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
  826. else:
  827. xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
  828. # standard XML-RPC wrappings
  829. if methodname:
  830. # a method call
  831. data = (
  832. xmlheader,
  833. "<methodCall>\n"
  834. "<methodName>", methodname, "</methodName>\n",
  835. data,
  836. "</methodCall>\n"
  837. )
  838. elif methodresponse:
  839. # a method response, or a fault structure
  840. data = (
  841. xmlheader,
  842. "<methodResponse>\n",
  843. data,
  844. "</methodResponse>\n"
  845. )
  846. else:
  847. return data # return as is
  848. return "".join(data)
  849. ##
  850. # Convert an XML-RPC packet to a Python object. If the XML-RPC packet
  851. # represents a fault condition, this function raises a Fault exception.
  852. #
  853. # @param data An XML-RPC packet, given as an 8-bit string.
  854. # @return A tuple containing the unpacked data, and the method name
  855. # (None if not present).
  856. # @see Fault
  857. def loads(data, use_datetime=False, use_builtin_types=False):
  858. """data -> unmarshalled data, method name
  859. Convert an XML-RPC packet to unmarshalled data plus a method
  860. name (None if not present).
  861. If the XML-RPC packet represents a fault condition, this function
  862. raises a Fault exception.
  863. """
  864. p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
  865. p.feed(data)
  866. p.close()
  867. return u.close(), u.getmethodname()
  868. ##
  869. # Encode a string using the gzip content encoding such as specified by the
  870. # Content-Encoding: gzip
  871. # in the HTTP header, as described in RFC 1952
  872. #
  873. # @param data the unencoded data
  874. # @return the encoded data
  875. def gzip_encode(data):
  876. """data -> gzip encoded data
  877. Encode data using the gzip content encoding as described in RFC 1952
  878. """
  879. if not gzip:
  880. raise NotImplementedError
  881. f = BytesIO()
  882. with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf:
  883. gzf.write(data)
  884. return f.getvalue()
  885. ##
  886. # Decode a string using the gzip content encoding such as specified by the
  887. # Content-Encoding: gzip
  888. # in the HTTP header, as described in RFC 1952
  889. #
  890. # @param data The encoded data
  891. # @keyparam max_decode Maximum bytes to decode (20 MiB default), use negative
  892. # values for unlimited decoding
  893. # @return the unencoded data
  894. # @raises ValueError if data is not correctly coded.
  895. # @raises ValueError if max gzipped payload length exceeded
  896. def gzip_decode(data, max_decode=20971520):
  897. """gzip encoded data -> unencoded data
  898. Decode data using the gzip content encoding as described in RFC 1952
  899. """
  900. if not gzip:
  901. raise NotImplementedError
  902. with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf:
  903. try:
  904. if max_decode < 0: # no limit
  905. decoded = gzf.read()
  906. else:
  907. decoded = gzf.read(max_decode + 1)
  908. except OSError:
  909. raise ValueError("invalid data")
  910. if max_decode >= 0 and len(decoded) > max_decode:
  911. raise ValueError("max gzipped payload length exceeded")
  912. return decoded
  913. ##
  914. # Return a decoded file-like object for the gzip encoding
  915. # as described in RFC 1952.
  916. #
  917. # @param response A stream supporting a read() method
  918. # @return a file-like object that the decoded data can be read() from
  919. class GzipDecodedResponse(gzip.GzipFile if gzip else object):
  920. """a file-like object to decode a response encoded with the gzip
  921. method, as described in RFC 1952.
  922. """
  923. def __init__(self, response):
  924. #response doesn't support tell() and read(), required by
  925. #GzipFile
  926. if not gzip:
  927. raise NotImplementedError
  928. self.io = BytesIO(response.read())
  929. gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io)
  930. def close(self):
  931. try:
  932. gzip.GzipFile.close(self)
  933. finally:
  934. self.io.close()
  935. # --------------------------------------------------------------------
  936. # request dispatcher
  937. class _Method:
  938. # some magic to bind an XML-RPC method to an RPC server.
  939. # supports "nested" methods (e.g. examples.getStateName)
  940. def __init__(self, send, name):
  941. self.__send = send
  942. self.__name = name
  943. def __getattr__(self, name):
  944. return _Method(self.__send, "%s.%s" % (self.__name, name))
  945. def __call__(self, *args):
  946. return self.__send(self.__name, args)
  947. ##
  948. # Standard transport class for XML-RPC over HTTP.
  949. # <p>
  950. # You can create custom transports by subclassing this method, and
  951. # overriding selected methods.
  952. class Transport:
  953. """Handles an HTTP transaction to an XML-RPC server."""
  954. # client identifier (may be overridden)
  955. user_agent = "Python-xmlrpc/%s" % __version__
  956. #if true, we'll request gzip encoding
  957. accept_gzip_encoding = True
  958. # if positive, encode request using gzip if it exceeds this threshold
  959. # note that many servers will get confused, so only use it if you know
  960. # that they can decode such a request
  961. encode_threshold = None #None = don't encode
  962. def __init__(self, use_datetime=False, use_builtin_types=False,
  963. *, headers=()):
  964. self._use_datetime = use_datetime
  965. self._use_builtin_types = use_builtin_types
  966. self._connection = (None, None)
  967. self._headers = list(headers)
  968. self._extra_headers = []
  969. ##
  970. # Send a complete request, and parse the response.
  971. # Retry request if a cached connection has disconnected.
  972. #
  973. # @param host Target host.
  974. # @param handler Target PRC handler.
  975. # @param request_body XML-RPC request body.
  976. # @param verbose Debugging flag.
  977. # @return Parsed response.
  978. def request(self, host, handler, request_body, verbose=False):
  979. #retry request once if cached connection has gone cold
  980. for i in (0, 1):
  981. try:
  982. return self.single_request(host, handler, request_body, verbose)
  983. except http.client.RemoteDisconnected:
  984. if i:
  985. raise
  986. except OSError as e:
  987. if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED,
  988. errno.EPIPE):
  989. raise
  990. def single_request(self, host, handler, request_body, verbose=False):
  991. # issue XML-RPC request
  992. try:
  993. http_conn = self.send_request(host, handler, request_body, verbose)
  994. resp = http_conn.getresponse()
  995. if resp.status == 200:
  996. self.verbose = verbose
  997. return self.parse_response(resp)
  998. except Fault:
  999. raise
  1000. except Exception:
  1001. #All unexpected errors leave connection in
  1002. # a strange state, so we clear it.
  1003. self.close()
  1004. raise
  1005. #We got an error response.
  1006. #Discard any response data and raise exception
  1007. if resp.getheader("content-length", ""):
  1008. resp.read()
  1009. raise ProtocolError(
  1010. host + handler,
  1011. resp.status, resp.reason,
  1012. dict(resp.getheaders())
  1013. )
  1014. ##
  1015. # Create parser.
  1016. #
  1017. # @return A 2-tuple containing a parser and an unmarshaller.
  1018. def getparser(self):
  1019. # get parser and unmarshaller
  1020. return getparser(use_datetime=self._use_datetime,
  1021. use_builtin_types=self._use_builtin_types)
  1022. ##
  1023. # Get authorization info from host parameter
  1024. # Host may be a string, or a (host, x509-dict) tuple; if a string,
  1025. # it is checked for a "user:pw@host" format, and a "Basic
  1026. # Authentication" header is added if appropriate.
  1027. #
  1028. # @param host Host descriptor (URL or (URL, x509 info) tuple).
  1029. # @return A 3-tuple containing (actual host, extra headers,
  1030. # x509 info). The header and x509 fields may be None.
  1031. def get_host_info(self, host):
  1032. x509 = {}
  1033. if isinstance(host, tuple):
  1034. host, x509 = host
  1035. auth, host = urllib.parse._splituser(host)
  1036. if auth:
  1037. auth = urllib.parse.unquote_to_bytes(auth)
  1038. auth = base64.encodebytes(auth).decode("utf-8")
  1039. auth = "".join(auth.split()) # get rid of whitespace
  1040. extra_headers = [
  1041. ("Authorization", "Basic " + auth)
  1042. ]
  1043. else:
  1044. extra_headers = []
  1045. return host, extra_headers, x509
  1046. ##
  1047. # Connect to server.
  1048. #
  1049. # @param host Target host.
  1050. # @return An HTTPConnection object
  1051. def make_connection(self, host):
  1052. #return an existing connection if possible. This allows
  1053. #HTTP/1.1 keep-alive.
  1054. if self._connection and host == self._connection[0]:
  1055. return self._connection[1]
  1056. # create a HTTP connection object from a host descriptor
  1057. chost, self._extra_headers, x509 = self.get_host_info(host)
  1058. self._connection = host, http.client.HTTPConnection(chost)
  1059. return self._connection[1]
  1060. ##
  1061. # Clear any cached connection object.
  1062. # Used in the event of socket errors.
  1063. #
  1064. def close(self):
  1065. host, connection = self._connection
  1066. if connection:
  1067. self._connection = (None, None)
  1068. connection.close()
  1069. ##
  1070. # Send HTTP request.
  1071. #
  1072. # @param host Host descriptor (URL or (URL, x509 info) tuple).
  1073. # @param handler Target RPC handler (a path relative to host)
  1074. # @param request_body The XML-RPC request body
  1075. # @param debug Enable debugging if debug is true.
  1076. # @return An HTTPConnection.
  1077. def send_request(self, host, handler, request_body, debug):
  1078. connection = self.make_connection(host)
  1079. headers = self._headers + self._extra_headers
  1080. if debug:
  1081. connection.set_debuglevel(1)
  1082. if self.accept_gzip_encoding and gzip:
  1083. connection.putrequest("POST", handler, skip_accept_encoding=True)
  1084. headers.append(("Accept-Encoding", "gzip"))
  1085. else:
  1086. connection.putrequest("POST", handler)
  1087. headers.append(("Content-Type", "text/xml"))
  1088. headers.append(("User-Agent", self.user_agent))
  1089. self.send_headers(connection, headers)
  1090. self.send_content(connection, request_body)
  1091. return connection
  1092. ##
  1093. # Send request headers.
  1094. # This function provides a useful hook for subclassing
  1095. #
  1096. # @param connection httpConnection.
  1097. # @param headers list of key,value pairs for HTTP headers
  1098. def send_headers(self, connection, headers):
  1099. for key, val in headers:
  1100. connection.putheader(key, val)
  1101. ##
  1102. # Send request body.
  1103. # This function provides a useful hook for subclassing
  1104. #
  1105. # @param connection httpConnection.
  1106. # @param request_body XML-RPC request body.
  1107. def send_content(self, connection, request_body):
  1108. #optionally encode the request
  1109. if (self.encode_threshold is not None and
  1110. self.encode_threshold < len(request_body) and
  1111. gzip):
  1112. connection.putheader("Content-Encoding", "gzip")
  1113. request_body = gzip_encode(request_body)
  1114. connection.putheader("Content-Length", str(len(request_body)))
  1115. connection.endheaders(request_body)
  1116. ##
  1117. # Parse response.
  1118. #
  1119. # @param file Stream.
  1120. # @return Response tuple and target method.
  1121. def parse_response(self, response):
  1122. # read response data from httpresponse, and parse it
  1123. # Check for new http response object, otherwise it is a file object.
  1124. if hasattr(response, 'getheader'):
  1125. if response.getheader("Content-Encoding", "") == "gzip":
  1126. stream = GzipDecodedResponse(response)
  1127. else:
  1128. stream = response
  1129. else:
  1130. stream = response
  1131. p, u = self.getparser()
  1132. while 1:
  1133. data = stream.read(1024)
  1134. if not data:
  1135. break
  1136. if self.verbose:
  1137. print("body:", repr(data))
  1138. p.feed(data)
  1139. if stream is not response:
  1140. stream.close()
  1141. p.close()
  1142. return u.close()
  1143. ##
  1144. # Standard transport class for XML-RPC over HTTPS.
  1145. class SafeTransport(Transport):
  1146. """Handles an HTTPS transaction to an XML-RPC server."""
  1147. def __init__(self, use_datetime=False, use_builtin_types=False,
  1148. *, headers=(), context=None):
  1149. super().__init__(use_datetime=use_datetime,
  1150. use_builtin_types=use_builtin_types,
  1151. headers=headers)
  1152. self.context = context
  1153. # FIXME: mostly untested
  1154. def make_connection(self, host):
  1155. if self._connection and host == self._connection[0]:
  1156. return self._connection[1]
  1157. if not hasattr(http.client, "HTTPSConnection"):
  1158. raise NotImplementedError(
  1159. "your version of http.client doesn't support HTTPS")
  1160. # create a HTTPS connection object from a host descriptor
  1161. # host may be a string, or a (host, x509-dict) tuple
  1162. chost, self._extra_headers, x509 = self.get_host_info(host)
  1163. self._connection = host, http.client.HTTPSConnection(chost,
  1164. None, context=self.context, **(x509 or {}))
  1165. return self._connection[1]
  1166. ##
  1167. # Standard server proxy. This class establishes a virtual connection
  1168. # to an XML-RPC server.
  1169. # <p>
  1170. # This class is available as ServerProxy and Server. New code should
  1171. # use ServerProxy, to avoid confusion.
  1172. #
  1173. # @def ServerProxy(uri, **options)
  1174. # @param uri The connection point on the server.
  1175. # @keyparam transport A transport factory, compatible with the
  1176. # standard transport class.
  1177. # @keyparam encoding The default encoding used for 8-bit strings
  1178. # (default is UTF-8).
  1179. # @keyparam verbose Use a true value to enable debugging output.
  1180. # (printed to standard output).
  1181. # @see Transport
  1182. class ServerProxy:
  1183. """uri [,options] -> a logical connection to an XML-RPC server
  1184. uri is the connection point on the server, given as
  1185. scheme://host/target.
  1186. The standard implementation always supports the "http" scheme. If
  1187. SSL socket support is available (Python 2.0), it also supports
  1188. "https".
  1189. If the target part and the slash preceding it are both omitted,
  1190. "/RPC2" is assumed.
  1191. The following options can be given as keyword arguments:
  1192. transport: a transport factory
  1193. encoding: the request encoding (default is UTF-8)
  1194. All 8-bit strings passed to the server proxy are assumed to use
  1195. the given encoding.
  1196. """
  1197. def __init__(self, uri, transport=None, encoding=None, verbose=False,
  1198. allow_none=False, use_datetime=False, use_builtin_types=False,
  1199. *, headers=(), context=None):
  1200. # establish a "logical" server connection
  1201. # get the url
  1202. p = urllib.parse.urlsplit(uri)
  1203. if p.scheme not in ("http", "https"):
  1204. raise OSError("unsupported XML-RPC protocol")
  1205. self.__host = p.netloc
  1206. self.__handler = urllib.parse.urlunsplit(["", "", *p[2:]])
  1207. if not self.__handler:
  1208. self.__handler = "/RPC2"
  1209. if transport is None:
  1210. if p.scheme == "https":
  1211. handler = SafeTransport
  1212. extra_kwargs = {"context": context}
  1213. else:
  1214. handler = Transport
  1215. extra_kwargs = {}
  1216. transport = handler(use_datetime=use_datetime,
  1217. use_builtin_types=use_builtin_types,
  1218. headers=headers,
  1219. **extra_kwargs)
  1220. self.__transport = transport
  1221. self.__encoding = encoding or 'utf-8'
  1222. self.__verbose = verbose
  1223. self.__allow_none = allow_none
  1224. def __close(self):
  1225. self.__transport.close()
  1226. def __request(self, methodname, params):
  1227. # call a method on the remote server
  1228. request = dumps(params, methodname, encoding=self.__encoding,
  1229. allow_none=self.__allow_none).encode(self.__encoding, 'xmlcharrefreplace')
  1230. response = self.__transport.request(
  1231. self.__host,
  1232. self.__handler,
  1233. request,
  1234. verbose=self.__verbose
  1235. )
  1236. if len(response) == 1:
  1237. response = response[0]
  1238. return response
  1239. def __repr__(self):
  1240. return (
  1241. "<%s for %s%s>" %
  1242. (self.__class__.__name__, self.__host, self.__handler)
  1243. )
  1244. def __getattr__(self, name):
  1245. # magic method dispatcher
  1246. return _Method(self.__request, name)
  1247. # note: to call a remote object with a non-standard name, use
  1248. # result getattr(server, "strange-python-name")(args)
  1249. def __call__(self, attr):
  1250. """A workaround to get special attributes on the ServerProxy
  1251. without interfering with the magic __getattr__
  1252. """
  1253. if attr == "close":
  1254. return self.__close
  1255. elif attr == "transport":
  1256. return self.__transport
  1257. raise AttributeError("Attribute %r not found" % (attr,))
  1258. def __enter__(self):
  1259. return self
  1260. def __exit__(self, *args):
  1261. self.__close()
  1262. # compatibility
  1263. Server = ServerProxy
  1264. # --------------------------------------------------------------------
  1265. # test code
  1266. if __name__ == "__main__":
  1267. # simple test program (from the XML-RPC specification)
  1268. # local server, available from Lib/xmlrpc/server.py
  1269. server = ServerProxy("http://localhost:8000")
  1270. try:
  1271. print(server.currentTime.getCurrentTime())
  1272. except Error as v:
  1273. print("ERROR", v)
  1274. multi = MultiCall(server)
  1275. multi.getData()
  1276. multi.pow(2,9)
  1277. multi.add(1,2)
  1278. try:
  1279. for response in multi():
  1280. print(response)
  1281. except Error as v:
  1282. print("ERROR", v)