blob: d584971822dbb4d23a50e0929f8cdcd4fdfb10b6 [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. Kuchling10a16de2005-12-04 16:34:40 +0000162 def __init__(self, allow_none):
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
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000166
Guido van Rossumd0641422005-02-03 15:01:24 +0000167 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000168 """Registers an instance to respond to XML-RPC requests.
169
170 Only one instance can be installed at a time.
171
172 If the registered instance has a _dispatch method then that
173 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000174 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000175 e.g. instance._dispatch('add',(2,3))
176
177 If the registered instance does not have a _dispatch method
178 then the instance will be searched to find a matching method
179 and, if found, will be called. Methods beginning with an '_'
180 are considered private and will not be called by
181 SimpleXMLRPCServer.
182
183 If a registered function matches a XML-RPC request, then it
184 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000185
186 If the optional allow_dotted_names argument is true and the
187 instance does not have a _dispatch method, method names
188 containing dots are supported and resolved, as long as none of
189 the name segments start with an '_'.
190
191 *** SECURITY WARNING: ***
192
193 Enabling the allow_dotted_names options allows intruders
194 to access your module's global variables and may allow
195 intruders to execute arbitrary code on your machine. Only
196 use this option on a secure, closed network.
197
Fredrik Lundhb329b712001-09-17 17:35:21 +0000198 """
199
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000200 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000201 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000202
203 def register_function(self, function, name = None):
204 """Registers a function to respond to XML-RPC requests.
205
206 The optional name argument can be used to set a Unicode name
207 for the function.
208 """
209
210 if name is None:
211 name = function.__name__
212 self.funcs[name] = function
213
214 def register_introspection_functions(self):
215 """Registers the XML-RPC introspection methods in the system
216 namespace.
217
218 see http://xmlrpc.usefulinc.com/doc/reserved.html
219 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000220
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000221 self.funcs.update({'system.listMethods' : self.system_listMethods,
222 'system.methodSignature' : self.system_methodSignature,
223 'system.methodHelp' : self.system_methodHelp})
224
225 def register_multicall_functions(self):
226 """Registers the XML-RPC multicall method in the system
227 namespace.
228
229 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000230
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000231 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000232
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000233 def _marshaled_dispatch(self, data, dispatch_method = None):
234 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000235
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000236 XML-RPC methods are dispatched from the marshalled (XML) data
237 using the _dispatch method and the result is returned as
238 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000239 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000240 SimpleXMLRPCRequestHandler.do_POST) but overriding the
241 existing method through subclassing is the prefered means
242 of changing method dispatch behavior.
243 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000244
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000245 params, method = xmlrpclib.loads(data)
246
247 # generate response
Fredrik Lundhb329b712001-09-17 17:35:21 +0000248 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000249 if dispatch_method is not None:
250 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000251 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000252 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000253 # wrap response in a singleton tuple
254 response = (response,)
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000255 response = xmlrpclib.dumps(response, methodresponse=1,
256 allow_none = self.allow_none)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000257 except Fault, fault:
258 response = xmlrpclib.dumps(fault)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000259 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000260 # report exception back to server
261 response = xmlrpclib.dumps(
262 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
263 )
264
265 return response
266
267 def system_listMethods(self):
268 """system.listMethods() => ['add', 'subtract', 'multiple']
269
270 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000271
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000272 methods = self.funcs.keys()
273 if self.instance is not None:
274 # Instance can implement _listMethod to return a list of
275 # methods
276 if hasattr(self.instance, '_listMethods'):
277 methods = remove_duplicates(
278 methods + self.instance._listMethods()
279 )
280 # if the instance has a _dispatch method then we
281 # don't have enough information to provide a list
282 # of methods
283 elif not hasattr(self.instance, '_dispatch'):
284 methods = remove_duplicates(
285 methods + list_public_methods(self.instance)
286 )
287 methods.sort()
288 return methods
Tim Peters2c60f7a2003-01-29 03:49:43 +0000289
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000290 def system_methodSignature(self, method_name):
291 """system.methodSignature('add') => [double, int, int]
292
Brett Cannonb9b5f162004-10-03 23:21:44 +0000293 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000294 above example, the add method takes two integers as arguments
295 and returns a double result.
296
297 This server does NOT support system.methodSignature."""
298
299 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000300
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000301 return 'signatures not supported'
302
303 def system_methodHelp(self, method_name):
304 """system.methodHelp('add') => "Adds two integers together"
305
306 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000307
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000308 method = None
309 if self.funcs.has_key(method_name):
310 method = self.funcs[method_name]
311 elif self.instance is not None:
312 # Instance can implement _methodHelp to return help for a method
313 if hasattr(self.instance, '_methodHelp'):
314 return self.instance._methodHelp(method_name)
315 # if the instance has a _dispatch method then we
316 # don't have enough information to provide help
317 elif not hasattr(self.instance, '_dispatch'):
318 try:
319 method = resolve_dotted_attribute(
320 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000321 method_name,
322 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000323 )
324 except AttributeError:
325 pass
326
327 # Note that we aren't checking that the method actually
328 # be a callable object of some kind
329 if method is None:
330 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000331 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000332 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000333 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000334
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000335 def system_multicall(self, call_list):
336 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
337[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000338
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000339 Allows the caller to package multiple XML-RPC calls into a single
340 request.
341
Tim Peters2c60f7a2003-01-29 03:49:43 +0000342 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000343 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000344
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000345 results = []
346 for call in call_list:
347 method_name = call['methodName']
348 params = call['params']
349
350 try:
351 # XXX A marshalling error in any response will fail the entire
352 # multicall. If someone cares they should fix this.
353 results.append([self._dispatch(method_name, params)])
354 except Fault, fault:
355 results.append(
356 {'faultCode' : fault.faultCode,
357 'faultString' : fault.faultString}
358 )
359 except:
360 results.append(
361 {'faultCode' : 1,
362 'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)}
363 )
364 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000365
Fredrik Lundhb329b712001-09-17 17:35:21 +0000366 def _dispatch(self, method, params):
367 """Dispatches the XML-RPC method.
368
369 XML-RPC calls are forwarded to a registered function that
370 matches the called XML-RPC method name. If no such function
371 exists then the call is forwarded to the registered instance,
372 if available.
373
374 If the registered instance has a _dispatch method then that
375 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000376 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000377 e.g. instance._dispatch('add',(2,3))
378
379 If the registered instance does not have a _dispatch method
380 then the instance will be searched to find a matching method
381 and, if found, will be called.
382
383 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000384 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000385 """
386
Fredrik Lundhb329b712001-09-17 17:35:21 +0000387 func = None
388 try:
389 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000390 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000391 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000392 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000393 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000394 if hasattr(self.instance, '_dispatch'):
395 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000396 else:
397 # call instance method directly
398 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000399 func = resolve_dotted_attribute(
400 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000401 method,
402 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000403 )
404 except AttributeError:
405 pass
406
407 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000408 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000409 else:
410 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000411
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000412class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
413 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000414
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000415 Handles all HTTP POST requests and attempts to decode them as
416 XML-RPC requests.
417 """
418
419 def do_POST(self):
420 """Handles the HTTP POST request.
421
422 Attempts to interpret all HTTP POST requests as XML-RPC calls,
423 which are forwarded to the server's _dispatch method for handling.
424 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000425
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000426 try:
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000427 # Get arguments by reading body of request.
428 # We read this in chunks to avoid straining
429 # socket.read(); around the 10 or 15Mb mark, some platforms
430 # begin to have problems (bug #792570).
431 max_chunk_size = 10*1024*1024
432 size_remaining = int(self.headers["content-length"])
433 L = []
434 while size_remaining:
435 chunk_size = min(size_remaining, max_chunk_size)
436 L.append(self.rfile.read(chunk_size))
437 size_remaining -= len(L[-1])
438 data = ''.join(L)
439
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000440 # In previous versions of SimpleXMLRPCServer, _dispatch
441 # could be overridden in this class, instead of in
442 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
443 # check to see if a subclass implements _dispatch and dispatch
444 # using that method if present.
445 response = self.server._marshaled_dispatch(
446 data, getattr(self, '_dispatch', None)
447 )
448 except: # This should only happen if the module is buggy
449 # internal error, report as HTTP server error
450 self.send_response(500)
451 self.end_headers()
452 else:
453 # got a valid XML RPC response
454 self.send_response(200)
455 self.send_header("Content-type", "text/xml")
456 self.send_header("Content-length", str(len(response)))
457 self.end_headers()
458 self.wfile.write(response)
459
460 # shut down the connection
461 self.wfile.flush()
462 self.connection.shutdown(1)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000463
Fredrik Lundhb329b712001-09-17 17:35:21 +0000464 def log_request(self, code='-', size='-'):
465 """Selectively log an accepted request."""
466
467 if self.server.logRequests:
468 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
469
Tim Peters2c60f7a2003-01-29 03:49:43 +0000470class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000471 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000472 """Simple XML-RPC server.
473
474 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000475 to be installed to handle requests. The default implementation
476 attempts to dispatch XML-RPC calls to the functions or instance
477 installed in the server. Override the _dispatch method inhereted
478 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000479 """
480
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000481 allow_reuse_address = True
482
Fredrik Lundhb329b712001-09-17 17:35:21 +0000483 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000484 logRequests=1, allow_none=False):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000485 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000486
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000487 SimpleXMLRPCDispatcher.__init__(self, allow_none)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000488 SocketServer.TCPServer.__init__(self, addr, requestHandler)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000489
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000490 # [Bug #1222790] If possible, set close-on-exec flag; if a
491 # method spawns a subprocess, the subprocess shouldn't have
492 # the listening socket open.
493 if hasattr(fcntl, 'FD_CLOEXEC'):
494 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
495 flags |= fcntl.FD_CLOEXEC
496 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
497
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000498class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
499 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000500
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000501 def __init__(self, allow_none=False):
502 SimpleXMLRPCDispatcher.__init__(self, allow_none)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000503
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000504 def handle_xmlrpc(self, request_text):
505 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000506
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000507 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000508
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000509 print 'Content-Type: text/xml'
510 print 'Content-Length: %d' % len(response)
511 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000512 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000513
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000514 def handle_get(self):
515 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000516
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000517 Default implementation indicates an error because
518 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000519 """
520
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000521 code = 400
522 message, explain = \
523 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000524
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000525 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
526 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000527 'code' : code,
528 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000529 'explain' : explain
530 }
531 print 'Status: %d %s' % (code, message)
532 print 'Content-Type: text/html'
533 print 'Content-Length: %d' % len(response)
534 print
Neal Norwitz732911f2003-06-29 04:16:28 +0000535 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000536
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000537 def handle_request(self, request_text = None):
538 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000539
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000540 If no XML data is given then it is read from stdin. The resulting
541 XML-RPC response is printed to stdout along with the correct HTTP
542 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000543 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000544
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000545 if request_text is None and \
546 os.environ.get('REQUEST_METHOD', None) == 'GET':
547 self.handle_get()
548 else:
549 # POST data is normally available through stdin
550 if request_text is None:
Tim Peters2c60f7a2003-01-29 03:49:43 +0000551 request_text = sys.stdin.read()
Fredrik Lundhb329b712001-09-17 17:35:21 +0000552
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000553 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000554
Fredrik Lundhb329b712001-09-17 17:35:21 +0000555if __name__ == '__main__':
556 server = SimpleXMLRPCServer(("localhost", 8000))
557 server.register_function(pow)
558 server.register_function(lambda x,y: x+y, 'add')
559 server.serve_forever()