PageRenderTime 63ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/xmlrpclib.py

https://bitbucket.org/kcr/pypy
Python | 1639 lines | 1510 code | 10 blank | 119 comment | 7 complexity | 25691f40dd8728e2de192bc8c63f498a MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file