blob: 052a8e4aed8607d5adb9d03eea07848f2f43dc88 [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
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000107import os, fcntl
Fredrik Lundhb329b712001-09-17 17:35:21 +0000108
Guido van Rossumd0641422005-02-03 15:01:24 +0000109def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000110 """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Fredrik Lundhb329b712001-09-17 17:35:21 +0000111
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000112 Resolves a dotted attribute name to an object. Raises
113 an AttributeError if any attribute in the chain starts with a '_'.
Guido van Rossumd0641422005-02-03 15:01:24 +0000114
115 If the optional allow_dotted_names argument is false, dots are not
116 supported and this function operates similar to getattr(obj, attr).
Fredrik Lundhb329b712001-09-17 17:35:21 +0000117 """
118
Guido van Rossumd0641422005-02-03 15:01:24 +0000119 if allow_dotted_names:
120 attrs = attr.split('.')
121 else:
122 attrs = [attr]
123
124 for i in attrs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000125 if i.startswith('_'):
126 raise AttributeError(
127 'attempt to access private attribute "%s"' % i
128 )
129 else:
130 obj = getattr(obj,i)
131 return obj
Fredrik Lundhb329b712001-09-17 17:35:21 +0000132
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000133def list_public_methods(obj):
134 """Returns a list of attribute strings, found in the specified
135 object, which represent callable attributes"""
136
137 return [member for member in dir(obj)
138 if not member.startswith('_') and
139 callable(getattr(obj, member))]
140
141def remove_duplicates(lst):
142 """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
143
144 Returns a copy of a list without duplicates. Every list
145 item must be hashable and the order of the items in the
146 resulting list is not defined.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000147 """
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000148 u = {}
149 for x in lst:
150 u[x] = 1
151
152 return u.keys()
153
154class SimpleXMLRPCDispatcher:
155 """Mix-in class that dispatches XML-RPC requests.
156
157 This class is used to register XML-RPC method handlers
158 and then to dispatch them. There should never be any
159 reason to instantiate this class directly.
160 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000161
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000162 def __init__(self, allow_none, encoding):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000163 self.funcs = {}
164 self.instance = None
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000165 self.allow_none = allow_none
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000166 self.encoding = encoding
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000167
Guido van Rossumd0641422005-02-03 15:01:24 +0000168 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000169 """Registers an instance to respond to XML-RPC requests.
170
171 Only one instance can be installed at a time.
172
173 If the registered instance has a _dispatch method then that
174 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000175 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000176 e.g. instance._dispatch('add',(2,3))
177
178 If the registered instance does not have a _dispatch method
179 then the instance will be searched to find a matching method
180 and, if found, will be called. Methods beginning with an '_'
181 are considered private and will not be called by
182 SimpleXMLRPCServer.
183
184 If a registered function matches a XML-RPC request, then it
185 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000186
187 If the optional allow_dotted_names argument is true and the
188 instance does not have a _dispatch method, method names
189 containing dots are supported and resolved, as long as none of
190 the name segments start with an '_'.
191
192 *** SECURITY WARNING: ***
193
194 Enabling the allow_dotted_names options allows intruders
195 to access your module's global variables and may allow
196 intruders to execute arbitrary code on your machine. Only
197 use this option on a secure, closed network.
198
Fredrik Lundhb329b712001-09-17 17:35:21 +0000199 """
200
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000201 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000202 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000203
204 def register_function(self, function, name = None):
205 """Registers a function to respond to XML-RPC requests.
206
207 The optional name argument can be used to set a Unicode name
208 for the function.
209 """
210
211 if name is None:
212 name = function.__name__
213 self.funcs[name] = function
214
215 def register_introspection_functions(self):
216 """Registers the XML-RPC introspection methods in the system
217 namespace.
218
219 see http://xmlrpc.usefulinc.com/doc/reserved.html
220 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000221
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000222 self.funcs.update({'system.listMethods' : self.system_listMethods,
223 'system.methodSignature' : self.system_methodSignature,
224 'system.methodHelp' : self.system_methodHelp})
225
226 def register_multicall_functions(self):
227 """Registers the XML-RPC multicall method in the system
228 namespace.
229
230 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000231
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000232 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000233
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000234 def _marshaled_dispatch(self, data, dispatch_method = None):
235 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000236
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000237 XML-RPC methods are dispatched from the marshalled (XML) data
238 using the _dispatch method and the result is returned as
239 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000240 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000241 SimpleXMLRPCRequestHandler.do_POST) but overriding the
242 existing method through subclassing is the prefered means
243 of changing method dispatch behavior.
244 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000245
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000246 params, method = xmlrpclib.loads(data)
247
248 # generate response
Fredrik Lundhb329b712001-09-17 17:35:21 +0000249 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000250 if dispatch_method is not None:
251 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000252 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000253 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000254 # wrap response in a singleton tuple
255 response = (response,)
Tim Peters536cf992005-12-25 23:18:31 +0000256 response = xmlrpclib.dumps(response, methodresponse=1,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000257 allow_none=self.allow_none, encoding=self.encoding)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000258 except Fault, fault:
Tim Peters536cf992005-12-25 23:18:31 +0000259 response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000260 encoding=self.encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000261 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000262 # report exception back to server
263 response = xmlrpclib.dumps(
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000264 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
265 encoding=self.encoding, allow_none=self.allow_none,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000266 )
267
268 return response
269
270 def system_listMethods(self):
271 """system.listMethods() => ['add', 'subtract', 'multiple']
272
273 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000274
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000275 methods = self.funcs.keys()
276 if self.instance is not None:
277 # Instance can implement _listMethod to return a list of
278 # methods
279 if hasattr(self.instance, '_listMethods'):
280 methods = remove_duplicates(
281 methods + self.instance._listMethods()
282 )
283 # if the instance has a _dispatch method then we
284 # don't have enough information to provide a list
285 # of methods
286 elif not hasattr(self.instance, '_dispatch'):
287 methods = remove_duplicates(
288 methods + list_public_methods(self.instance)
289 )
290 methods.sort()
291 return methods
Tim Peters2c60f7a2003-01-29 03:49:43 +0000292
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000293 def system_methodSignature(self, method_name):
294 """system.methodSignature('add') => [double, int, int]
295
Brett Cannonb9b5f162004-10-03 23:21:44 +0000296 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000297 above example, the add method takes two integers as arguments
298 and returns a double result.
299
300 This server does NOT support system.methodSignature."""
301
302 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000303
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000304 return 'signatures not supported'
305
306 def system_methodHelp(self, method_name):
307 """system.methodHelp('add') => "Adds two integers together"
308
309 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000310
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000311 method = None
312 if self.funcs.has_key(method_name):
313 method = self.funcs[method_name]
314 elif self.instance is not None:
315 # Instance can implement _methodHelp to return help for a method
316 if hasattr(self.instance, '_methodHelp'):
317 return self.instance._methodHelp(method_name)
318 # if the instance has a _dispatch method then we
319 # don't have enough information to provide help
320 elif not hasattr(self.instance, '_dispatch'):
321 try:
322 method = resolve_dotted_attribute(
323 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000324 method_name,
325 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000326 )
327 except AttributeError:
328 pass
329
330 # Note that we aren't checking that the method actually
331 # be a callable object of some kind
332 if method is None:
333 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000334 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000335 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000336 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000337
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000338 def system_multicall(self, call_list):
339 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
340[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000341
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000342 Allows the caller to package multiple XML-RPC calls into a single
343 request.
344
Tim Peters2c60f7a2003-01-29 03:49:43 +0000345 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000346 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000347
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000348 results = []
349 for call in call_list:
350 method_name = call['methodName']
351 params = call['params']
352
353 try:
354 # XXX A marshalling error in any response will fail the entire
355 # multicall. If someone cares they should fix this.
356 results.append([self._dispatch(method_name, params)])
357 except Fault, fault:
358 results.append(
359 {'faultCode' : fault.faultCode,
360 'faultString' : fault.faultString}
361 )
362 except:
363 results.append(
364 {'faultCode' : 1,
365 'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)}
366 )
367 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000368
Fredrik Lundhb329b712001-09-17 17:35:21 +0000369 def _dispatch(self, method, params):
370 """Dispatches the XML-RPC method.
371
372 XML-RPC calls are forwarded to a registered function that
373 matches the called XML-RPC method name. If no such function
374 exists then the call is forwarded to the registered instance,
375 if available.
376
377 If the registered instance has a _dispatch method then that
378 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000379 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000380 e.g. instance._dispatch('add',(2,3))
381
382 If the registered instance does not have a _dispatch method
383 then the instance will be searched to find a matching method
384 and, if found, will be called.
385
386 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000387 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000388 """
389
Fredrik Lundhb329b712001-09-17 17:35:21 +0000390 func = None
391 try:
392 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000393 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000394 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000395 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000396 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000397 if hasattr(self.instance, '_dispatch'):
398 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000399 else:
400 # call instance method directly
401 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000402 func = resolve_dotted_attribute(
403 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000404 method,
405 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000406 )
407 except AttributeError:
408 pass
409
410 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000411 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000412 else:
413 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000414
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000415class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
416 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000417
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000418 Handles all HTTP POST requests and attempts to decode them as
419 XML-RPC requests.
420 """
421
422 def do_POST(self):
423 """Handles the HTTP POST request.
424
425 Attempts to interpret all HTTP POST requests as XML-RPC calls,
426 which are forwarded to the server's _dispatch method for handling.
427 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000428
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000429 try:
Tim Peters536cf992005-12-25 23:18:31 +0000430 # Get arguments by reading body of request.
431 # We read this in chunks to avoid straining
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000432 # socket.read(); around the 10 or 15Mb mark, some platforms
433 # begin to have problems (bug #792570).
434 max_chunk_size = 10*1024*1024
435 size_remaining = int(self.headers["content-length"])
436 L = []
437 while size_remaining:
438 chunk_size = min(size_remaining, max_chunk_size)
439 L.append(self.rfile.read(chunk_size))
440 size_remaining -= len(L[-1])
441 data = ''.join(L)
442
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000443 # In previous versions of SimpleXMLRPCServer, _dispatch
444 # could be overridden in this class, instead of in
445 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
446 # check to see if a subclass implements _dispatch and dispatch
447 # using that method if present.
448 response = self.server._marshaled_dispatch(
449 data, getattr(self, '_dispatch', None)
450 )
451 except: # This should only happen if the module is buggy
452 # internal error, report as HTTP server error
453 self.send_response(500)
454 self.end_headers()
455 else:
456 # got a valid XML RPC response
457 self.send_response(200)
458 self.send_header("Content-type", "text/xml")
459 self.send_header("Content-length", str(len(response)))
460 self.end_headers()
461 self.wfile.write(response)
462
463 # shut down the connection
464 self.wfile.flush()
465 self.connection.shutdown(1)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000466
Fredrik Lundhb329b712001-09-17 17:35:21 +0000467 def log_request(self, code='-', size='-'):
468 """Selectively log an accepted request."""
469
470 if self.server.logRequests:
471 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
472
Tim Peters2c60f7a2003-01-29 03:49:43 +0000473class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000474 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000475 """Simple XML-RPC server.
476
477 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000478 to be installed to handle requests. The default implementation
479 attempts to dispatch XML-RPC calls to the functions or instance
480 installed in the server. Override the _dispatch method inhereted
481 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000482 """
483
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000484 allow_reuse_address = True
485
Fredrik Lundhb329b712001-09-17 17:35:21 +0000486 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000487 logRequests=True, allow_none=False, encoding=None):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000488 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000489
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000490 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000491 SocketServer.TCPServer.__init__(self, addr, requestHandler)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000492
Tim Peters536cf992005-12-25 23:18:31 +0000493 # [Bug #1222790] If possible, set close-on-exec flag; if a
494 # method spawns a subprocess, the subprocess shouldn't have
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000495 # the listening socket open.
496 if hasattr(fcntl, 'FD_CLOEXEC'):
497 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
498 flags |= fcntl.FD_CLOEXEC
499 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
500
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000501class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
502 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000503
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000504 def __init__(self, allow_none=False, encoding=None):
505 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000506
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000507 def handle_xmlrpc(self, request_text):
508 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000509
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000510 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000511
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000512 print 'Content-Type: text/xml'
513 print 'Content-Length: %d' % len(response)
514 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000515 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000516
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000517 def handle_get(self):
518 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000519
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000520 Default implementation indicates an error because
521 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000522 """
523
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000524 code = 400
525 message, explain = \
526 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000527
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000528 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
529 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000530 'code' : code,
531 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000532 'explain' : explain
533 }
534 print 'Status: %d %s' % (code, message)
535 print 'Content-Type: text/html'
536 print 'Content-Length: %d' % len(response)
537 print
Neal Norwitz732911f2003-06-29 04:16:28 +0000538 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000539
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000540 def handle_request(self, request_text = None):
541 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000542
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000543 If no XML data is given then it is read from stdin. The resulting
544 XML-RPC response is printed to stdout along with the correct HTTP
545 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000546 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000547
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000548 if request_text is None and \
549 os.environ.get('REQUEST_METHOD', None) == 'GET':
550 self.handle_get()
551 else:
552 # POST data is normally available through stdin
553 if request_text is None:
Tim Peters2c60f7a2003-01-29 03:49:43 +0000554 request_text = sys.stdin.read()
Fredrik Lundhb329b712001-09-17 17:35:21 +0000555
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000556 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000557
Fredrik Lundhb329b712001-09-17 17:35:21 +0000558if __name__ == '__main__':
559 server = SimpleXMLRPCServer(("localhost", 8000))
560 server.register_function(pow)
561 server.register_function(lambda x,y: x+y, 'add')
562 server.serve_forever()