mirror of
https://github.com/python/cpython.git
synced 2024-12-12 03:04:15 +08:00
d59da4b432
svn+ssh://pythondev@svn.python.org/python/branches/p3yk ................ r55413 | fred.drake | 2007-05-17 12:30:10 -0700 (Thu, 17 May 2007) | 1 line fix argument name in documentation; match the implementation ................ r55430 | jack.diederich | 2007-05-18 06:39:59 -0700 (Fri, 18 May 2007) | 1 line Implements class decorators, PEP 3129. ................ r55432 | guido.van.rossum | 2007-05-18 08:09:41 -0700 (Fri, 18 May 2007) | 2 lines obsubmit. ................ r55434 | guido.van.rossum | 2007-05-18 09:39:10 -0700 (Fri, 18 May 2007) | 3 lines Fix bug in test_inspect. (I presume this is how it should be fixed; Jack Diedrich, please verify.) ................ r55460 | brett.cannon | 2007-05-20 00:31:57 -0700 (Sun, 20 May 2007) | 4 lines Remove the imageop module. With imgfile already removed in Python 3.0 and rgbimg gone in Python 2.6 the unit tests themselves were made worthless. Plus third-party libraries perform the same function much better. ................ r55469 | neal.norwitz | 2007-05-20 11:28:20 -0700 (Sun, 20 May 2007) | 118 lines Merged revisions 55324-55467 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r55348 | georg.brandl | 2007-05-15 13:19:34 -0700 (Tue, 15 May 2007) | 4 lines HTML-escape the plain traceback in cgitb's HTML output, to prevent the traceback inadvertently or maliciously closing the comment and injecting HTML into the error page. ........ r55372 | neal.norwitz | 2007-05-15 21:33:50 -0700 (Tue, 15 May 2007) | 6 lines Port rev 55353 from Guido: Add what looks like a necessary call to PyErr_NoMemory() when PyMem_MALLOC() fails. Will backport. ........ r55377 | neal.norwitz | 2007-05-15 22:06:33 -0700 (Tue, 15 May 2007) | 1 line Mention removal of some directories for obsolete platforms ........ r55380 | brett.cannon | 2007-05-15 22:50:03 -0700 (Tue, 15 May 2007) | 2 lines Change the maintainer of the BeOS port. ........ r55383 | georg.brandl | 2007-05-16 06:44:18 -0700 (Wed, 16 May 2007) | 2 lines Bug #1719995: don't use deprecated method in sets example. ........ r55386 | neal.norwitz | 2007-05-16 13:05:11 -0700 (Wed, 16 May 2007) | 5 lines Fix bug in marshal where bad data would cause a segfault due to lack of an infinite recursion check. Contributed by Damien Miller at Google. ........ r55389 | brett.cannon | 2007-05-16 15:42:29 -0700 (Wed, 16 May 2007) | 6 lines Remove the gopherlib module. It has been raising a DeprecationWarning since Python 2.5. Also remove gopher support from urllib/urllib2. As both imported gopherlib the usage of the support would have raised a DeprecationWarning. ........ r55394 | raymond.hettinger | 2007-05-16 18:08:04 -0700 (Wed, 16 May 2007) | 1 line calendar.py gets no benefit from xrange() instead of range() ........ r55395 | brett.cannon | 2007-05-16 19:02:56 -0700 (Wed, 16 May 2007) | 3 lines Complete deprecation of BaseException.message. Some subclasses were directly accessing the message attribute instead of using the descriptor. ........ r55396 | neal.norwitz | 2007-05-16 23:11:36 -0700 (Wed, 16 May 2007) | 4 lines Reduce the max stack depth to see if this fixes the segfaults on Windows and some other boxes. If this is successful, this rev should be backported. I'm not sure how close to the limit we should push this. ........ r55397 | neal.norwitz | 2007-05-16 23:23:50 -0700 (Wed, 16 May 2007) | 4 lines Set the depth to something very small to try to determine if the crashes on Windows are really due to the stack size or possibly some other problem. ........ r55398 | neal.norwitz | 2007-05-17 00:04:46 -0700 (Thu, 17 May 2007) | 4 lines Last try for tweaking the max stack depth. 5000 was the original value, 4000 didn't work either. 1000 does work on Windows. If 2000 works, that will hopefully be a reasonable balance. ........ r55412 | fred.drake | 2007-05-17 12:29:58 -0700 (Thu, 17 May 2007) | 1 line fix argument name in documentation; match the implementation ........ r55427 | neal.norwitz | 2007-05-17 22:47:16 -0700 (Thu, 17 May 2007) | 1 line Verify neither dumps or loads overflow the stack and segfault. ........ r55446 | collin.winter | 2007-05-18 16:11:24 -0700 (Fri, 18 May 2007) | 1 line Backport PEP 3110's new 'except' syntax to 2.6. ........ r55448 | raymond.hettinger | 2007-05-18 18:11:16 -0700 (Fri, 18 May 2007) | 1 line Improvements to NamedTuple's implementation, tests, and documentation ........ r55449 | raymond.hettinger | 2007-05-18 18:50:11 -0700 (Fri, 18 May 2007) | 1 line Fix beginner mistake -- don't mix spaces and tabs. ........ r55450 | neal.norwitz | 2007-05-18 20:48:47 -0700 (Fri, 18 May 2007) | 1 line Clear data so random memory does not get freed. Will backport. ........ r55452 | neal.norwitz | 2007-05-18 21:34:55 -0700 (Fri, 18 May 2007) | 3 lines Whoops, need to pay attention to those test failures. Move the clear to *before* the first use, not after. ........ r55453 | neal.norwitz | 2007-05-18 21:35:52 -0700 (Fri, 18 May 2007) | 1 line Give some clue as to what happened if the test fails. ........ r55455 | georg.brandl | 2007-05-19 11:09:26 -0700 (Sat, 19 May 2007) | 2 lines Fix docstring for add_package in site.py. ........ r55458 | brett.cannon | 2007-05-20 00:09:50 -0700 (Sun, 20 May 2007) | 2 lines Remove the rgbimg module. It has been deprecated since Python 2.5. ........ r55465 | nick.coghlan | 2007-05-20 04:12:49 -0700 (Sun, 20 May 2007) | 1 line Fix typo in example (should be backported, but my maintenance branch is woefully out of date) ........ ................ r55472 | brett.cannon | 2007-05-20 12:06:18 -0700 (Sun, 20 May 2007) | 2 lines Remove imageop from the Windows build process. ................ r55486 | neal.norwitz | 2007-05-20 23:59:52 -0700 (Sun, 20 May 2007) | 1 line Remove callable() builtin ................ r55506 | neal.norwitz | 2007-05-22 00:43:29 -0700 (Tue, 22 May 2007) | 78 lines Merged revisions 55468-55505 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r55468 | neal.norwitz | 2007-05-20 11:06:27 -0700 (Sun, 20 May 2007) | 1 line rotor is long gone. ........ r55470 | neal.norwitz | 2007-05-20 11:43:00 -0700 (Sun, 20 May 2007) | 1 line Update directories/files at the top-level. ........ r55471 | brett.cannon | 2007-05-20 12:05:06 -0700 (Sun, 20 May 2007) | 2 lines Try to remove rgbimg from Windows builds. ........ r55474 | brett.cannon | 2007-05-20 16:17:38 -0700 (Sun, 20 May 2007) | 4 lines Remove the macfs module. This led to the deprecation of macostools.touched(); it completely relied on macfs and is a no-op on OS X according to code comments. ........ r55476 | brett.cannon | 2007-05-20 16:56:18 -0700 (Sun, 20 May 2007) | 3 lines Move imgfile import to the global namespace to trigger an import error ASAP to prevent creation of a test file. ........ r55477 | brett.cannon | 2007-05-20 16:57:38 -0700 (Sun, 20 May 2007) | 3 lines Cause posixfile to raise a DeprecationWarning. Documented as deprecated since Ptyhon 1.5. ........ r55479 | andrew.kuchling | 2007-05-20 17:03:15 -0700 (Sun, 20 May 2007) | 1 line Note removed modules ........ r55481 | martin.v.loewis | 2007-05-20 21:35:47 -0700 (Sun, 20 May 2007) | 2 lines Add Alexandre Vassalotti. ........ r55482 | george.yoshida | 2007-05-20 21:41:21 -0700 (Sun, 20 May 2007) | 4 lines fix against r55474 [Remove the macfs module] Remove "libmacfs.tex" from Makefile.deps and mac/mac.tex. ........ r55487 | raymond.hettinger | 2007-05-21 01:13:35 -0700 (Mon, 21 May 2007) | 1 line Replace assertion with straight error-checking. ........ r55489 | raymond.hettinger | 2007-05-21 09:40:10 -0700 (Mon, 21 May 2007) | 1 line Allow all alphanumeric and underscores in type and field names. ........ r55490 | facundo.batista | 2007-05-21 10:32:32 -0700 (Mon, 21 May 2007) | 5 lines Added timeout support to HTTPSConnection, through the socket.create_connection function. Also added a small test for this, and updated NEWS file. ........ r55495 | georg.brandl | 2007-05-21 13:34:16 -0700 (Mon, 21 May 2007) | 2 lines Patch #1686487: you can now pass any mapping after '**' in function calls. ........ r55502 | neal.norwitz | 2007-05-21 23:03:36 -0700 (Mon, 21 May 2007) | 1 line Document new params to HTTPSConnection ........ r55504 | neal.norwitz | 2007-05-22 00:16:10 -0700 (Tue, 22 May 2007) | 1 line Stop using METH_OLDARGS ........ r55505 | neal.norwitz | 2007-05-22 00:16:44 -0700 (Tue, 22 May 2007) | 1 line Stop using METH_OLDARGS implicitly ........ ................
597 lines
21 KiB
Python
597 lines
21 KiB
Python
"""Simple XML-RPC Server.
|
|
|
|
This module can be used to create simple XML-RPC servers
|
|
by creating a server and either installing functions, a
|
|
class instance, or by extending the SimpleXMLRPCServer
|
|
class.
|
|
|
|
It can also be used to handle XML-RPC requests in a CGI
|
|
environment using CGIXMLRPCRequestHandler.
|
|
|
|
A list of possible usage patterns follows:
|
|
|
|
1. Install functions:
|
|
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_function(pow)
|
|
server.register_function(lambda x,y: x+y, 'add')
|
|
server.serve_forever()
|
|
|
|
2. Install an instance:
|
|
|
|
class MyFuncs:
|
|
def __init__(self):
|
|
# make all of the sys functions available through sys.func_name
|
|
import sys
|
|
self.sys = sys
|
|
def _listMethods(self):
|
|
# implement this method so that system.listMethods
|
|
# knows to advertise the sys methods
|
|
return list_public_methods(self) + \
|
|
['sys.' + method for method in list_public_methods(self.sys)]
|
|
def pow(self, x, y): return pow(x, y)
|
|
def add(self, x, y) : return x + y
|
|
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_introspection_functions()
|
|
server.register_instance(MyFuncs())
|
|
server.serve_forever()
|
|
|
|
3. Install an instance with custom dispatch method:
|
|
|
|
class Math:
|
|
def _listMethods(self):
|
|
# this method must be present for system.listMethods
|
|
# to work
|
|
return ['add', 'pow']
|
|
def _methodHelp(self, method):
|
|
# this method must be present for system.methodHelp
|
|
# to work
|
|
if method == 'add':
|
|
return "add(2,3) => 5"
|
|
elif method == 'pow':
|
|
return "pow(x, y[, z]) => number"
|
|
else:
|
|
# By convention, return empty
|
|
# string if no help is available
|
|
return ""
|
|
def _dispatch(self, method, params):
|
|
if method == 'pow':
|
|
return pow(*params)
|
|
elif method == 'add':
|
|
return params[0] + params[1]
|
|
else:
|
|
raise 'bad method'
|
|
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_introspection_functions()
|
|
server.register_instance(Math())
|
|
server.serve_forever()
|
|
|
|
4. Subclass SimpleXMLRPCServer:
|
|
|
|
class MathServer(SimpleXMLRPCServer):
|
|
def _dispatch(self, method, params):
|
|
try:
|
|
# We are forcing the 'export_' prefix on methods that are
|
|
# callable through XML-RPC to prevent potential security
|
|
# problems
|
|
func = getattr(self, 'export_' + method)
|
|
except AttributeError:
|
|
raise Exception('method "%s" is not supported' % method)
|
|
else:
|
|
return func(*params)
|
|
|
|
def export_add(self, x, y):
|
|
return x + y
|
|
|
|
server = MathServer(("localhost", 8000))
|
|
server.serve_forever()
|
|
|
|
5. CGI script:
|
|
|
|
server = CGIXMLRPCRequestHandler()
|
|
server.register_function(pow)
|
|
server.handle_request()
|
|
"""
|
|
|
|
# Written by Brian Quinlan (brian@sweetapp.com).
|
|
# Based on code written by Fredrik Lundh.
|
|
|
|
import xmlrpclib
|
|
from xmlrpclib import Fault
|
|
import SocketServer
|
|
import BaseHTTPServer
|
|
import sys
|
|
import os
|
|
try:
|
|
import fcntl
|
|
except ImportError:
|
|
fcntl = None
|
|
|
|
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
|
|
"""resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
|
|
|
|
Resolves a dotted attribute name to an object. Raises
|
|
an AttributeError if any attribute in the chain starts with a '_'.
|
|
|
|
If the optional allow_dotted_names argument is false, dots are not
|
|
supported and this function operates similar to getattr(obj, attr).
|
|
"""
|
|
|
|
if allow_dotted_names:
|
|
attrs = attr.split('.')
|
|
else:
|
|
attrs = [attr]
|
|
|
|
for i in attrs:
|
|
if i.startswith('_'):
|
|
raise AttributeError(
|
|
'attempt to access private attribute "%s"' % i
|
|
)
|
|
else:
|
|
obj = getattr(obj,i)
|
|
return obj
|
|
|
|
def list_public_methods(obj):
|
|
"""Returns a list of attribute strings, found in the specified
|
|
object, which represent callable attributes"""
|
|
|
|
return [member for member in dir(obj)
|
|
if not member.startswith('_') and
|
|
hasattr(getattr(obj, member), '__call__')]
|
|
|
|
def remove_duplicates(lst):
|
|
"""remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
|
|
|
|
Returns a copy of a list without duplicates. Every list
|
|
item must be hashable and the order of the items in the
|
|
resulting list is not defined.
|
|
"""
|
|
u = {}
|
|
for x in lst:
|
|
u[x] = 1
|
|
|
|
return u.keys()
|
|
|
|
class SimpleXMLRPCDispatcher:
|
|
"""Mix-in class that dispatches XML-RPC requests.
|
|
|
|
This class is used to register XML-RPC method handlers
|
|
and then to dispatch them. There should never be any
|
|
reason to instantiate this class directly.
|
|
"""
|
|
|
|
def __init__(self, allow_none, encoding):
|
|
self.funcs = {}
|
|
self.instance = None
|
|
self.allow_none = allow_none
|
|
self.encoding = encoding
|
|
|
|
def register_instance(self, instance, allow_dotted_names=False):
|
|
"""Registers an instance to respond to XML-RPC requests.
|
|
|
|
Only one instance can be installed at a time.
|
|
|
|
If the registered instance has a _dispatch method then that
|
|
method will be called with the name of the XML-RPC method and
|
|
its parameters as a tuple
|
|
e.g. instance._dispatch('add',(2,3))
|
|
|
|
If the registered instance does not have a _dispatch method
|
|
then the instance will be searched to find a matching method
|
|
and, if found, will be called. Methods beginning with an '_'
|
|
are considered private and will not be called by
|
|
SimpleXMLRPCServer.
|
|
|
|
If a registered function matches a XML-RPC request, then it
|
|
will be called instead of the registered instance.
|
|
|
|
If the optional allow_dotted_names argument is true and the
|
|
instance does not have a _dispatch method, method names
|
|
containing dots are supported and resolved, as long as none of
|
|
the name segments start with an '_'.
|
|
|
|
*** SECURITY WARNING: ***
|
|
|
|
Enabling the allow_dotted_names options allows intruders
|
|
to access your module's global variables and may allow
|
|
intruders to execute arbitrary code on your machine. Only
|
|
use this option on a secure, closed network.
|
|
|
|
"""
|
|
|
|
self.instance = instance
|
|
self.allow_dotted_names = allow_dotted_names
|
|
|
|
def register_function(self, function, name = None):
|
|
"""Registers a function to respond to XML-RPC requests.
|
|
|
|
The optional name argument can be used to set a Unicode name
|
|
for the function.
|
|
"""
|
|
|
|
if name is None:
|
|
name = function.__name__
|
|
self.funcs[name] = function
|
|
|
|
def register_introspection_functions(self):
|
|
"""Registers the XML-RPC introspection methods in the system
|
|
namespace.
|
|
|
|
see http://xmlrpc.usefulinc.com/doc/reserved.html
|
|
"""
|
|
|
|
self.funcs.update({'system.listMethods' : self.system_listMethods,
|
|
'system.methodSignature' : self.system_methodSignature,
|
|
'system.methodHelp' : self.system_methodHelp})
|
|
|
|
def register_multicall_functions(self):
|
|
"""Registers the XML-RPC multicall method in the system
|
|
namespace.
|
|
|
|
see http://www.xmlrpc.com/discuss/msgReader$1208"""
|
|
|
|
self.funcs.update({'system.multicall' : self.system_multicall})
|
|
|
|
def _marshaled_dispatch(self, data, dispatch_method = None):
|
|
"""Dispatches an XML-RPC method from marshalled (XML) data.
|
|
|
|
XML-RPC methods are dispatched from the marshalled (XML) data
|
|
using the _dispatch method and the result is returned as
|
|
marshalled data. For backwards compatibility, a dispatch
|
|
function can be provided as an argument (see comment in
|
|
SimpleXMLRPCRequestHandler.do_POST) but overriding the
|
|
existing method through subclassing is the prefered means
|
|
of changing method dispatch behavior.
|
|
"""
|
|
|
|
try:
|
|
params, method = xmlrpclib.loads(data)
|
|
|
|
# generate response
|
|
if dispatch_method is not None:
|
|
response = dispatch_method(method, params)
|
|
else:
|
|
response = self._dispatch(method, params)
|
|
# wrap response in a singleton tuple
|
|
response = (response,)
|
|
response = xmlrpclib.dumps(response, methodresponse=1,
|
|
allow_none=self.allow_none, encoding=self.encoding)
|
|
except Fault as fault:
|
|
response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
|
|
encoding=self.encoding)
|
|
except:
|
|
# report exception back to server
|
|
exc_type, exc_value, exc_tb = sys.exc_info()
|
|
response = xmlrpclib.dumps(
|
|
xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
|
|
encoding=self.encoding, allow_none=self.allow_none,
|
|
)
|
|
|
|
return response
|
|
|
|
def system_listMethods(self):
|
|
"""system.listMethods() => ['add', 'subtract', 'multiple']
|
|
|
|
Returns a list of the methods supported by the server."""
|
|
|
|
methods = self.funcs.keys()
|
|
if self.instance is not None:
|
|
# Instance can implement _listMethod to return a list of
|
|
# methods
|
|
if hasattr(self.instance, '_listMethods'):
|
|
methods = remove_duplicates(
|
|
methods + self.instance._listMethods()
|
|
)
|
|
# if the instance has a _dispatch method then we
|
|
# don't have enough information to provide a list
|
|
# of methods
|
|
elif not hasattr(self.instance, '_dispatch'):
|
|
methods = remove_duplicates(
|
|
methods + list_public_methods(self.instance)
|
|
)
|
|
methods.sort()
|
|
return methods
|
|
|
|
def system_methodSignature(self, method_name):
|
|
"""system.methodSignature('add') => [double, int, int]
|
|
|
|
Returns a list describing the signature of the method. In the
|
|
above example, the add method takes two integers as arguments
|
|
and returns a double result.
|
|
|
|
This server does NOT support system.methodSignature."""
|
|
|
|
# See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
|
|
|
|
return 'signatures not supported'
|
|
|
|
def system_methodHelp(self, method_name):
|
|
"""system.methodHelp('add') => "Adds two integers together"
|
|
|
|
Returns a string containing documentation for the specified method."""
|
|
|
|
method = None
|
|
if method_name in self.funcs:
|
|
method = self.funcs[method_name]
|
|
elif self.instance is not None:
|
|
# Instance can implement _methodHelp to return help for a method
|
|
if hasattr(self.instance, '_methodHelp'):
|
|
return self.instance._methodHelp(method_name)
|
|
# if the instance has a _dispatch method then we
|
|
# don't have enough information to provide help
|
|
elif not hasattr(self.instance, '_dispatch'):
|
|
try:
|
|
method = resolve_dotted_attribute(
|
|
self.instance,
|
|
method_name,
|
|
self.allow_dotted_names
|
|
)
|
|
except AttributeError:
|
|
pass
|
|
|
|
# Note that we aren't checking that the method actually
|
|
# be a callable object of some kind
|
|
if method is None:
|
|
return ""
|
|
else:
|
|
import pydoc
|
|
return pydoc.getdoc(method)
|
|
|
|
def system_multicall(self, call_list):
|
|
"""system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
|
|
[[4], ...]
|
|
|
|
Allows the caller to package multiple XML-RPC calls into a single
|
|
request.
|
|
|
|
See http://www.xmlrpc.com/discuss/msgReader$1208
|
|
"""
|
|
|
|
results = []
|
|
for call in call_list:
|
|
method_name = call['methodName']
|
|
params = call['params']
|
|
|
|
try:
|
|
# XXX A marshalling error in any response will fail the entire
|
|
# multicall. If someone cares they should fix this.
|
|
results.append([self._dispatch(method_name, params)])
|
|
except Fault as fault:
|
|
results.append(
|
|
{'faultCode' : fault.faultCode,
|
|
'faultString' : fault.faultString}
|
|
)
|
|
except:
|
|
exc_type, exc_value, exc_tb = sys.exc_info()
|
|
results.append(
|
|
{'faultCode' : 1,
|
|
'faultString' : "%s:%s" % (exc_type, exc_value)}
|
|
)
|
|
return results
|
|
|
|
def _dispatch(self, method, params):
|
|
"""Dispatches the XML-RPC method.
|
|
|
|
XML-RPC calls are forwarded to a registered function that
|
|
matches the called XML-RPC method name. If no such function
|
|
exists then the call is forwarded to the registered instance,
|
|
if available.
|
|
|
|
If the registered instance has a _dispatch method then that
|
|
method will be called with the name of the XML-RPC method and
|
|
its parameters as a tuple
|
|
e.g. instance._dispatch('add',(2,3))
|
|
|
|
If the registered instance does not have a _dispatch method
|
|
then the instance will be searched to find a matching method
|
|
and, if found, will be called.
|
|
|
|
Methods beginning with an '_' are considered private and will
|
|
not be called.
|
|
"""
|
|
|
|
func = None
|
|
try:
|
|
# check to see if a matching function has been registered
|
|
func = self.funcs[method]
|
|
except KeyError:
|
|
if self.instance is not None:
|
|
# check for a _dispatch method
|
|
if hasattr(self.instance, '_dispatch'):
|
|
return self.instance._dispatch(method, params)
|
|
else:
|
|
# call instance method directly
|
|
try:
|
|
func = resolve_dotted_attribute(
|
|
self.instance,
|
|
method,
|
|
self.allow_dotted_names
|
|
)
|
|
except AttributeError:
|
|
pass
|
|
|
|
if func is not None:
|
|
return func(*params)
|
|
else:
|
|
raise Exception('method "%s" is not supported' % method)
|
|
|
|
class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
|
|
"""Simple XML-RPC request handler class.
|
|
|
|
Handles all HTTP POST requests and attempts to decode them as
|
|
XML-RPC requests.
|
|
"""
|
|
|
|
# Class attribute listing the accessible path components;
|
|
# paths not on this list will result in a 404 error.
|
|
rpc_paths = ('/', '/RPC2')
|
|
|
|
def is_rpc_path_valid(self):
|
|
if self.rpc_paths:
|
|
return self.path in self.rpc_paths
|
|
else:
|
|
# If .rpc_paths is empty, just assume all paths are legal
|
|
return True
|
|
|
|
def do_POST(self):
|
|
"""Handles the HTTP POST request.
|
|
|
|
Attempts to interpret all HTTP POST requests as XML-RPC calls,
|
|
which are forwarded to the server's _dispatch method for handling.
|
|
"""
|
|
|
|
# Check that the path is legal
|
|
if not self.is_rpc_path_valid():
|
|
self.report_404()
|
|
return
|
|
|
|
try:
|
|
# Get arguments by reading body of request.
|
|
# We read this in chunks to avoid straining
|
|
# socket.read(); around the 10 or 15Mb mark, some platforms
|
|
# begin to have problems (bug #792570).
|
|
max_chunk_size = 10*1024*1024
|
|
size_remaining = int(self.headers["content-length"])
|
|
L = []
|
|
while size_remaining:
|
|
chunk_size = min(size_remaining, max_chunk_size)
|
|
L.append(self.rfile.read(chunk_size))
|
|
size_remaining -= len(L[-1])
|
|
data = ''.join(L)
|
|
|
|
# In previous versions of SimpleXMLRPCServer, _dispatch
|
|
# could be overridden in this class, instead of in
|
|
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
|
|
# check to see if a subclass implements _dispatch and dispatch
|
|
# using that method if present.
|
|
response = self.server._marshaled_dispatch(
|
|
data, getattr(self, '_dispatch', None)
|
|
)
|
|
except: # This should only happen if the module is buggy
|
|
# internal error, report as HTTP server error
|
|
self.send_response(500)
|
|
self.end_headers()
|
|
else:
|
|
# got a valid XML RPC response
|
|
self.send_response(200)
|
|
self.send_header("Content-type", "text/xml")
|
|
self.send_header("Content-length", str(len(response)))
|
|
self.end_headers()
|
|
self.wfile.write(response)
|
|
|
|
# shut down the connection
|
|
self.wfile.flush()
|
|
self.connection.shutdown(1)
|
|
|
|
def report_404 (self):
|
|
# Report a 404 error
|
|
self.send_response(404)
|
|
response = 'No such page'
|
|
self.send_header("Content-type", "text/plain")
|
|
self.send_header("Content-length", str(len(response)))
|
|
self.end_headers()
|
|
self.wfile.write(response)
|
|
# shut down the connection
|
|
self.wfile.flush()
|
|
self.connection.shutdown(1)
|
|
|
|
def log_request(self, code='-', size='-'):
|
|
"""Selectively log an accepted request."""
|
|
|
|
if self.server.logRequests:
|
|
BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
|
|
|
|
class SimpleXMLRPCServer(SocketServer.TCPServer,
|
|
SimpleXMLRPCDispatcher):
|
|
"""Simple XML-RPC server.
|
|
|
|
Simple XML-RPC server that allows functions and a single instance
|
|
to be installed to handle requests. The default implementation
|
|
attempts to dispatch XML-RPC calls to the functions or instance
|
|
installed in the server. Override the _dispatch method inhereted
|
|
from SimpleXMLRPCDispatcher to change this behavior.
|
|
"""
|
|
|
|
allow_reuse_address = True
|
|
|
|
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
|
|
logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
|
|
self.logRequests = logRequests
|
|
|
|
SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
|
|
SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
|
|
|
|
# [Bug #1222790] If possible, set close-on-exec flag; if a
|
|
# method spawns a subprocess, the subprocess shouldn't have
|
|
# the listening socket open.
|
|
if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
|
|
flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
|
|
flags |= fcntl.FD_CLOEXEC
|
|
fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
|
|
|
|
class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
|
|
"""Simple handler for XML-RPC data passed through CGI."""
|
|
|
|
def __init__(self, allow_none=False, encoding=None):
|
|
SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
|
|
|
|
def handle_xmlrpc(self, request_text):
|
|
"""Handle a single XML-RPC request"""
|
|
|
|
response = self._marshaled_dispatch(request_text)
|
|
|
|
print('Content-Type: text/xml')
|
|
print('Content-Length: %d' % len(response))
|
|
print()
|
|
sys.stdout.write(response)
|
|
|
|
def handle_get(self):
|
|
"""Handle a single HTTP GET request.
|
|
|
|
Default implementation indicates an error because
|
|
XML-RPC uses the POST method.
|
|
"""
|
|
|
|
code = 400
|
|
message, explain = \
|
|
BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
|
|
|
|
response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
|
|
{
|
|
'code' : code,
|
|
'message' : message,
|
|
'explain' : explain
|
|
}
|
|
print('Status: %d %s' % (code, message))
|
|
print('Content-Type: text/html')
|
|
print('Content-Length: %d' % len(response))
|
|
print()
|
|
sys.stdout.write(response)
|
|
|
|
def handle_request(self, request_text = None):
|
|
"""Handle a single XML-RPC request passed through a CGI post method.
|
|
|
|
If no XML data is given then it is read from stdin. The resulting
|
|
XML-RPC response is printed to stdout along with the correct HTTP
|
|
headers.
|
|
"""
|
|
|
|
if request_text is None and \
|
|
os.environ.get('REQUEST_METHOD', None) == 'GET':
|
|
self.handle_get()
|
|
else:
|
|
# POST data is normally available through stdin
|
|
if request_text is None:
|
|
request_text = sys.stdin.read()
|
|
|
|
self.handle_xmlrpc(request_text)
|
|
|
|
if __name__ == '__main__':
|
|
print('Running XML-RPC server on port 8000')
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_function(pow)
|
|
server.register_function(lambda x,y: x+y, 'add')
|
|
server.serve_forever()
|