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