client.py 47 KB

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