client.py 47 KB

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