blob: a0b44e1c986735bcddfb6627cf9e9cfea9f6c40f [file] [log] [blame]
Fredrik Lundhb329b712001-09-17 17:35:21 +00001"""Simple XML-RPC Server.
2
3This module can be used to create simple XML-RPC servers
4by creating a server and either installing functions, a
Martin v. Löwisd69663d2003-01-15 11:37:23 +00005class instance, or by extending the SimpleXMLRPCServer
Fredrik Lundhb329b712001-09-17 17:35:21 +00006class.
7
Martin v. Löwisd69663d2003-01-15 11:37:23 +00008It can also be used to handle XML-RPC requests in a CGI
9environment using CGIXMLRPCRequestHandler.
10
Fredrik Lundhb329b712001-09-17 17:35:21 +000011A list of possible usage patterns follows:
12
131. Install functions:
14
15server = SimpleXMLRPCServer(("localhost", 8000))
16server.register_function(pow)
17server.register_function(lambda x,y: x+y, 'add')
18server.serve_forever()
19
202. Install an instance:
21
22class MyFuncs:
23 def __init__(self):
24 # make all of the string functions available through
25 # string.func_name
26 import string
27 self.string = string
Martin v. Löwisd69663d2003-01-15 11:37:23 +000028 def _listMethods(self):
29 # implement this method so that system.listMethods
30 # knows to advertise the strings methods
31 return list_public_methods(self) + \
32 ['string.' + method for method in list_public_methods(self.string)]
Fredrik Lundhb329b712001-09-17 17:35:21 +000033 def pow(self, x, y): return pow(x, y)
34 def add(self, x, y) : return x + y
Tim Peters2c60f7a2003-01-29 03:49:43 +000035
Fredrik Lundhb329b712001-09-17 17:35:21 +000036server = SimpleXMLRPCServer(("localhost", 8000))
Martin v. Löwisd69663d2003-01-15 11:37:23 +000037server.register_introspection_functions()
Fredrik Lundhb329b712001-09-17 17:35:21 +000038server.register_instance(MyFuncs())
39server.serve_forever()
40
413. Install an instance with custom dispatch method:
42
43class Math:
Martin v. Löwisd69663d2003-01-15 11:37:23 +000044 def _listMethods(self):
45 # this method must be present for system.listMethods
46 # to work
47 return ['add', 'pow']
48 def _methodHelp(self, method):
49 # this method must be present for system.methodHelp
50 # to work
51 if method == 'add':
52 return "add(2,3) => 5"
53 elif method == 'pow':
54 return "pow(x, y[, z]) => number"
55 else:
56 # By convention, return empty
57 # string if no help is available
58 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +000059 def _dispatch(self, method, params):
60 if method == 'pow':
Martin v. Löwisd69663d2003-01-15 11:37:23 +000061 return pow(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +000062 elif method == 'add':
63 return params[0] + params[1]
64 else:
65 raise 'bad method'
Martin v. Löwisd69663d2003-01-15 11:37:23 +000066
Fredrik Lundhb329b712001-09-17 17:35:21 +000067server = SimpleXMLRPCServer(("localhost", 8000))
Martin v. Löwisd69663d2003-01-15 11:37:23 +000068server.register_introspection_functions()
Fredrik Lundhb329b712001-09-17 17:35:21 +000069server.register_instance(Math())
70server.serve_forever()
71
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000724. Subclass SimpleXMLRPCServer:
Fredrik Lundhb329b712001-09-17 17:35:21 +000073
Martin v. Löwisd69663d2003-01-15 11:37:23 +000074class MathServer(SimpleXMLRPCServer):
Fredrik Lundhb329b712001-09-17 17:35:21 +000075 def _dispatch(self, method, params):
76 try:
77 # We are forcing the 'export_' prefix on methods that are
78 # callable through XML-RPC to prevent potential security
79 # problems
80 func = getattr(self, 'export_' + method)
81 except AttributeError:
82 raise Exception('method "%s" is not supported' % method)
83 else:
Martin v. Löwisd69663d2003-01-15 11:37:23 +000084 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +000085
86 def export_add(self, x, y):
87 return x + y
88
Martin v. Löwisd69663d2003-01-15 11:37:23 +000089server = MathServer(("localhost", 8000))
Fredrik Lundhb329b712001-09-17 17:35:21 +000090server.serve_forever()
Martin v. Löwisd69663d2003-01-15 11:37:23 +000091
925. CGI script:
93
94server = CGIXMLRPCRequestHandler()
95server.register_function(pow)
96server.handle_request()
Fredrik Lundhb329b712001-09-17 17:35:21 +000097"""
98
99# Written by Brian Quinlan (brian@sweetapp.com).
100# Based on code written by Fredrik Lundh.
101
102import xmlrpclib
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000103from xmlrpclib import Fault
Fredrik Lundhb329b712001-09-17 17:35:21 +0000104import SocketServer
105import BaseHTTPServer
106import sys
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000107import os
108try:
109 import fcntl
110except ImportError:
111 fcntl = None
Fredrik Lundhb329b712001-09-17 17:35:21 +0000112
Guido van Rossumd0641422005-02-03 15:01:24 +0000113def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000114 """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Fredrik Lundhb329b712001-09-17 17:35:21 +0000115
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000116 Resolves a dotted attribute name to an object. Raises
117 an AttributeError if any attribute in the chain starts with a '_'.
Guido van Rossumd0641422005-02-03 15:01:24 +0000118
119 If the optional allow_dotted_names argument is false, dots are not
120 supported and this function operates similar to getattr(obj, attr).
Fredrik Lundhb329b712001-09-17 17:35:21 +0000121 """
122
Guido van Rossumd0641422005-02-03 15:01:24 +0000123 if allow_dotted_names:
124 attrs = attr.split('.')
125 else:
126 attrs = [attr]
127
128 for i in attrs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000129 if i.startswith('_'):
130 raise AttributeError(
131 'attempt to access private attribute "%s"' % i
132 )
133 else:
134 obj = getattr(obj,i)
135 return obj
Fredrik Lundhb329b712001-09-17 17:35:21 +0000136
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000137def list_public_methods(obj):
138 """Returns a list of attribute strings, found in the specified
139 object, which represent callable attributes"""
140
141 return [member for member in dir(obj)
142 if not member.startswith('_') and
143 callable(getattr(obj, member))]
144
145def remove_duplicates(lst):
146 """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
147
148 Returns a copy of a list without duplicates. Every list
149 item must be hashable and the order of the items in the
150 resulting list is not defined.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000151 """
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000152 u = {}
153 for x in lst:
154 u[x] = 1
155
156 return u.keys()
157
158class SimpleXMLRPCDispatcher:
159 """Mix-in class that dispatches XML-RPC requests.
160
161 This class is used to register XML-RPC method handlers
162 and then to dispatch them. There should never be any
163 reason to instantiate this class directly.
164 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000165
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000166 def __init__(self, allow_none, encoding):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000167 self.funcs = {}
168 self.instance = None
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000169 self.allow_none = allow_none
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000170 self.encoding = encoding
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000171
Guido van Rossumd0641422005-02-03 15:01:24 +0000172 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000173 """Registers an instance to respond to XML-RPC requests.
174
175 Only one instance can be installed at a time.
176
177 If the registered instance has a _dispatch method then that
178 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000179 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000180 e.g. instance._dispatch('add',(2,3))
181
182 If the registered instance does not have a _dispatch method
183 then the instance will be searched to find a matching method
184 and, if found, will be called. Methods beginning with an '_'
185 are considered private and will not be called by
186 SimpleXMLRPCServer.
187
188 If a registered function matches a XML-RPC request, then it
189 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000190
191 If the optional allow_dotted_names argument is true and the
192 instance does not have a _dispatch method, method names
193 containing dots are supported and resolved, as long as none of
194 the name segments start with an '_'.
195
196 *** SECURITY WARNING: ***
197
198 Enabling the allow_dotted_names options allows intruders
199 to access your module's global variables and may allow
200 intruders to execute arbitrary code on your machine. Only
201 use this option on a secure, closed network.
202
Fredrik Lundhb329b712001-09-17 17:35:21 +0000203 """
204
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000205 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000206 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000207
208 def register_function(self, function, name = None):
209 """Registers a function to respond to XML-RPC requests.
210
211 The optional name argument can be used to set a Unicode name
212 for the function.
213 """
214
215 if name is None:
216 name = function.__name__
217 self.funcs[name] = function
218
219 def register_introspection_functions(self):
220 """Registers the XML-RPC introspection methods in the system
221 namespace.
222
223 see http://xmlrpc.usefulinc.com/doc/reserved.html
224 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000225
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000226 self.funcs.update({'system.listMethods' : self.system_listMethods,
227 'system.methodSignature' : self.system_methodSignature,
228 'system.methodHelp' : self.system_methodHelp})
229
230 def register_multicall_functions(self):
231 """Registers the XML-RPC multicall method in the system
232 namespace.
233
234 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000235
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000236 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000237
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000238 def _marshaled_dispatch(self, data, dispatch_method = None):
239 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000240
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000241 XML-RPC methods are dispatched from the marshalled (XML) data
242 using the _dispatch method and the result is returned as
243 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000244 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000245 SimpleXMLRPCRequestHandler.do_POST) but overriding the
246 existing method through subclassing is the prefered means
247 of changing method dispatch behavior.
248 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000249
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000250 params, method = xmlrpclib.loads(data)
251
252 # generate response
Fredrik Lundhb329b712001-09-17 17:35:21 +0000253 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000254 if dispatch_method is not None:
255 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000256 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000257 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000258 # wrap response in a singleton tuple
259 response = (response,)
Tim Peters536cf992005-12-25 23:18:31 +0000260 response = xmlrpclib.dumps(response, methodresponse=1,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000261 allow_none=self.allow_none, encoding=self.encoding)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000262 except Fault, fault:
Tim Peters536cf992005-12-25 23:18:31 +0000263 response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000264 encoding=self.encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000265 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000266 # report exception back to server
267 response = xmlrpclib.dumps(
Neal Norwitzac3625f2006-03-17 05:49:33 +0000268 xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]),
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000269 encoding=self.encoding, allow_none=self.allow_none,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000270 )
271
272 return response
273
274 def system_listMethods(self):
275 """system.listMethods() => ['add', 'subtract', 'multiple']
276
277 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000278
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000279 methods = self.funcs.keys()
280 if self.instance is not None:
281 # Instance can implement _listMethod to return a list of
282 # methods
283 if hasattr(self.instance, '_listMethods'):
284 methods = remove_duplicates(
285 methods + self.instance._listMethods()
286 )
287 # if the instance has a _dispatch method then we
288 # don't have enough information to provide a list
289 # of methods
290 elif not hasattr(self.instance, '_dispatch'):
291 methods = remove_duplicates(
292 methods + list_public_methods(self.instance)
293 )
294 methods.sort()
295 return methods
Tim Peters2c60f7a2003-01-29 03:49:43 +0000296
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000297 def system_methodSignature(self, method_name):
298 """system.methodSignature('add') => [double, int, int]
299
Brett Cannonb9b5f162004-10-03 23:21:44 +0000300 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000301 above example, the add method takes two integers as arguments
302 and returns a double result.
303
304 This server does NOT support system.methodSignature."""
305
306 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000307
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000308 return 'signatures not supported'
309
310 def system_methodHelp(self, method_name):
311 """system.methodHelp('add') => "Adds two integers together"
312
313 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000314
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000315 method = None
316 if self.funcs.has_key(method_name):
317 method = self.funcs[method_name]
318 elif self.instance is not None:
319 # Instance can implement _methodHelp to return help for a method
320 if hasattr(self.instance, '_methodHelp'):
321 return self.instance._methodHelp(method_name)
322 # if the instance has a _dispatch method then we
323 # don't have enough information to provide help
324 elif not hasattr(self.instance, '_dispatch'):
325 try:
326 method = resolve_dotted_attribute(
327 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000328 method_name,
329 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000330 )
331 except AttributeError:
332 pass
333
334 # Note that we aren't checking that the method actually
335 # be a callable object of some kind
336 if method is None:
337 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000338 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000339 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000340 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000341
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000342 def system_multicall(self, call_list):
343 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
344[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000345
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000346 Allows the caller to package multiple XML-RPC calls into a single
347 request.
348
Tim Peters2c60f7a2003-01-29 03:49:43 +0000349 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000350 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000351
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000352 results = []
353 for call in call_list:
354 method_name = call['methodName']
355 params = call['params']
356
357 try:
358 # XXX A marshalling error in any response will fail the entire
359 # multicall. If someone cares they should fix this.
360 results.append([self._dispatch(method_name, params)])
361 except Fault, fault:
362 results.append(
363 {'faultCode' : fault.faultCode,
364 'faultString' : fault.faultString}
365 )
366 except:
367 results.append(
368 {'faultCode' : 1,
Neal Norwitzac3625f2006-03-17 05:49:33 +0000369 'faultString' : "%s:%s" % sys.exc_info()[:2]}
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000370 )
371 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000372
Fredrik Lundhb329b712001-09-17 17:35:21 +0000373 def _dispatch(self, method, params):
374 """Dispatches the XML-RPC method.
375
376 XML-RPC calls are forwarded to a registered function that
377 matches the called XML-RPC method name. If no such function
378 exists then the call is forwarded to the registered instance,
379 if available.
380
381 If the registered instance has a _dispatch method then that
382 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000383 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000384 e.g. instance._dispatch('add',(2,3))
385
386 If the registered instance does not have a _dispatch method
387 then the instance will be searched to find a matching method
388 and, if found, will be called.
389
390 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000391 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000392 """
393
Fredrik Lundhb329b712001-09-17 17:35:21 +0000394 func = None
395 try:
396 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000397 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000398 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000399 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000400 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000401 if hasattr(self.instance, '_dispatch'):
402 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000403 else:
404 # call instance method directly
405 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000406 func = resolve_dotted_attribute(
407 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000408 method,
409 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000410 )
411 except AttributeError:
412 pass
413
414 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000415 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000416 else:
417 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000418
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000419class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
420 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000421
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000422 Handles all HTTP POST requests and attempts to decode them as
423 XML-RPC requests.
424 """
425
426 def do_POST(self):
427 """Handles the HTTP POST request.
428
429 Attempts to interpret all HTTP POST requests as XML-RPC calls,
430 which are forwarded to the server's _dispatch method for handling.
431 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000432
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000433 try:
Tim Peters536cf992005-12-25 23:18:31 +0000434 # Get arguments by reading body of request.
435 # We read this in chunks to avoid straining
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000436 # socket.read(); around the 10 or 15Mb mark, some platforms
437 # begin to have problems (bug #792570).
438 max_chunk_size = 10*1024*1024
439 size_remaining = int(self.headers["content-length"])
440 L = []
441 while size_remaining:
442 chunk_size = min(size_remaining, max_chunk_size)
443 L.append(self.rfile.read(chunk_size))
444 size_remaining -= len(L[-1])
445 data = ''.join(L)
446
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000447 # In previous versions of SimpleXMLRPCServer, _dispatch
448 # could be overridden in this class, instead of in
449 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
450 # check to see if a subclass implements _dispatch and dispatch
451 # using that method if present.
452 response = self.server._marshaled_dispatch(
453 data, getattr(self, '_dispatch', None)
454 )
455 except: # This should only happen if the module is buggy
456 # internal error, report as HTTP server error
457 self.send_response(500)
458 self.end_headers()
459 else:
460 # got a valid XML RPC response
461 self.send_response(200)
462 self.send_header("Content-type", "text/xml")
463 self.send_header("Content-length", str(len(response)))
464 self.end_headers()
465 self.wfile.write(response)
466
467 # shut down the connection
468 self.wfile.flush()
469 self.connection.shutdown(1)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000470
Fredrik Lundhb329b712001-09-17 17:35:21 +0000471 def log_request(self, code='-', size='-'):
472 """Selectively log an accepted request."""
473
474 if self.server.logRequests:
475 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
476
Tim Peters2c60f7a2003-01-29 03:49:43 +0000477class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000478 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000479 """Simple XML-RPC server.
480
481 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000482 to be installed to handle requests. The default implementation
483 attempts to dispatch XML-RPC calls to the functions or instance
484 installed in the server. Override the _dispatch method inhereted
485 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000486 """
487
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000488 allow_reuse_address = True
489
Fredrik Lundhb329b712001-09-17 17:35:21 +0000490 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000491 logRequests=True, allow_none=False, encoding=None):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000492 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000493
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000494 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000495 SocketServer.TCPServer.__init__(self, addr, requestHandler)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000496
Tim Peters536cf992005-12-25 23:18:31 +0000497 # [Bug #1222790] If possible, set close-on-exec flag; if a
498 # method spawns a subprocess, the subprocess shouldn't have
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000499 # the listening socket open.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500 if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000501 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
502 flags |= fcntl.FD_CLOEXEC
503 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
504
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000505class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
506 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000507
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000508 def __init__(self, allow_none=False, encoding=None):
509 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000510
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000511 def handle_xmlrpc(self, request_text):
512 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000513
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000514 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000515
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000516 print 'Content-Type: text/xml'
517 print 'Content-Length: %d' % len(response)
518 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000519 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000520
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000521 def handle_get(self):
522 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000523
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000524 Default implementation indicates an error because
525 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000526 """
527
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000528 code = 400
529 message, explain = \
530 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000531
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000532 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
533 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000534 'code' : code,
535 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000536 'explain' : explain
537 }
538 print 'Status: %d %s' % (code, message)
539 print 'Content-Type: text/html'
540 print 'Content-Length: %d' % len(response)
541 print
Neal Norwitz732911f2003-06-29 04:16:28 +0000542 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000543
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000544 def handle_request(self, request_text = None):
545 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000546
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000547 If no XML data is given then it is read from stdin. The resulting
548 XML-RPC response is printed to stdout along with the correct HTTP
549 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000550 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000551
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000552 if request_text is None and \
553 os.environ.get('REQUEST_METHOD', None) == 'GET':
554 self.handle_get()
555 else:
556 # POST data is normally available through stdin
557 if request_text is None:
Tim Peters2c60f7a2003-01-29 03:49:43 +0000558 request_text = sys.stdin.read()
Fredrik Lundhb329b712001-09-17 17:35:21 +0000559
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000560 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000561
Fredrik Lundhb329b712001-09-17 17:35:21 +0000562if __name__ == '__main__':
563 server = SimpleXMLRPCServer(("localhost", 8000))
564 server.register_function(pow)
565 server.register_function(lambda x,y: x+y, 'add')
566 server.serve_forever()