def CreateApp(self, name): """ Creates new app. @param name: Name of an app. @type name: C{str} @return: Instance id of an app. @rtype: C{int} """ if not self.Apps: return 0 if name not in self.Apps: return 0 id= int(random.getrandbits(16)) print self.Apps[name] if not self.instances: self.instances= {} self.instances[id]= (self.Apps[name](), name,) dispatcher= SimpleXMLRPCDispatcher() dispatcher.register_introspection_functions() dispatcher.register_instance(self.instances[id][0]) self.server.add_dispatcher( "/"+str(id), dispatcher) return id
class WSGIXMLRPCApplication(object): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=[]): """Create windmill xmlrpc dispatcher""" self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def handler(self, environ, start_response): """XMLRPC service for windmill browser core to communicate with""" if environ['REQUEST_METHOD'] == 'POST': return self.handle_POST(environ, start_response) else: start_response("400 Bad request", [('Content-Type', 'text/plain')]) return [''] def handle_POST(self, environ, start_response): """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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: # Get arguments by reading body of request. # We read this in chunks to avoid straining length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) # 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 # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error start_response("500 Server error", [('Content-Type', 'text/plain')]) return [] else: # got a valid XML RPC response start_response("200 OK", [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)),)]) return [response] def __call__(self, environ, start_response): return self.handler(environ, start_response)
def handler(request, response, methods): response.session_id = None # no sessions for xmlrpc dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) for method in methods: dispatcher.register_function(method) dispatcher.register_introspection_functions() response.headers['Content-Type'] = 'text/xml' dispatch = getattr(dispatcher, '_dispatch', None) return dispatcher._marshaled_dispatch(request.body.read(), dispatch)
class Server(Thread): """ XML-RPC server. """ @LogCall() def __init__(self, requestHandler, host="localhost", port=8400): """ Initializes server. @param requestHandler: Request handler for base class calls. @type requestHandler: C{AppsHandler} @param host: Host where to bind. @type host: C{str} @param port: Port where to bind. @type port: C{int} @return: Instance of self. @rtype: C{Server} """ Thread.__init__(self) self.server = MultiPathXMLRPCServer((host, port), requestHandler=RHandler) self.requestHandler= requestHandler(self.server, False) self.dispatcher= SimpleXMLRPCDispatcher() self.dispatcher.register_introspection_functions() self.dispatcher.register_instance(self.requestHandler) self.server.add_dispatcher("/", self.dispatcher) @LogCall({"level": INFO}) def run(self): """ Runs server. @return: Nothing @rtype: C{None} """ self.server.serve_forever() @LogCall({"level": INFO}) def __del__(self): """ Stops server. @return: Nothing @rtype: C{None} """ self.server.shutdown() def GetRequestHandler(self): """ Gets base request handler used with this server. @return: Request handler used with this server. @rtype: C{AppsHandler} """ return self.requestHandler
class WSGIXMLRPCApplication(object): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=()): """Create windmill xmlrpc dispatcher""" try: self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) except TypeError: # python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() @Request.application def handler(self, request): if request.method == 'POST': return self.handle_POST(request) else: return BadRequest() def handle_POST(self, request): """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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: # Read the data from the request data = request.get_data() # 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 # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None)) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error return InternalServerError() else: # got a valid XML RPC response return Response(response, mimetype='text/xml') def __call__(self, environ, start_response): return self.handler(environ, start_response)
class XMLRPCApplication(RestApplication): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=[]): """Create windmill xmlrpc dispatcher""" try: self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) except TypeError: # python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def POST(self, request, *path): """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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: data = str(request.body) # 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 # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error return Response500() else: # got a valid XML RPC response return XMLResponse(response)
class WSGIXMLRPCApplication: def __init__(self,instance=None,methods=[]): self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,encoding=None) if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def __call__(self,environ,start_response): if environ["REQUEST_METHOD"] == "POST": return self.handle_post(environ,start_response) else: start_response("400 Bad request",[("Content-Type","text/plain")]) return [''] def handle_post(self,environ,start_response): try: max_chunk_size = 10*1024*1024 size_remaining = int(environ["CONTENT_LENGTH"]) L = [] rfile = environ['wsgi.input'] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]) data = ''.join(L) data = self.decode_request_content(data,environ,start_response) if isinstance(data, list): return data response = self.dispatcher._marshaled_dispatch(data) except Exception, e: start_response("%d %s" % (500,_RESPONSE_STATUSES[500]),[ ("Content-length", '') ]) return [] else:
class XMLRPCDispatcher(Resource): '''A Resource that knows how to host an XMLRPCObject and serve it''' def __init__(self, application, request, response, session, instance=None, methods=[], allow_none=True, encoding=None): '''initializes this dispatcher which can handle XMLRPC requests.''' if not instance: raise ValueError("You must pass in a non-null object which we will serve") super(XMLRPCDispatcher, self).__init__(application, request, response, session) self.dispatcher = SimpleXMLRPCDispatcher(allow_none=allow_none, encoding=encoding) self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() self.dispatcher.register_multicall_functions() @POST @Route("/{path:.*}") def post(self, path): ''' Attempts to process all posts as XMLRPC Requests which are then dispatched to the XMLRPCObject. Most of the code was taken from SimpleXMLRPCServer with modifications to make it compatible with Gates ''' try: data = self.request.body response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) except Exception as e: # This should only happen if the module is buggy # internal error, report as Internal HTTP Server error traceback.print_exc(e) abort(500, "XMLRPC Application Error! You shouldn't be seeing this. We're sorry.") else: # We got a valid XML RPC response self.response.type = "text/xml" self.response.write(response)
# response.write("The following methods are available:<ul>") # methods = server.system_listMethods() # # for method in methods: # # right now, my version of SimpleXMLRPCDispatcher always # # returns "signatures not supported"... :( # # but, in an ideal world it will tell users what args are expected # sig = server.system_methodSignature(method) # # # this just reads your docblock, so fill it in! ## help = server.system_methodHelp(method) # help = '' # # response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) # # response.write("</ul>") # response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') # # response['Content-length'] = str(len(response.content)) return response server = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) server.register_introspection_functions() def ping(name, site_url, entry_url, rss_url): logging.info('ping %s %s %s %s' % (name, site_url, entry_url, rss_url)) return 'ping %s %s %s %s' % (name, site_url, entry_url, rss_url) server.register_function(ping, 'weblogUpdates.ping')
) def decode_request_content(self, data): encoding = self.headers.get("content-encoding", "identity").lower() if encoding != "gzip": self.send_response(501, "encoding %r not supported" % encoding) return SimpleXMLRPCRequestHandler.decode_request_content(self, data) if __name__ == "__main__": server = MultiPathXMLRPCServer(("0.0.0.0", 12345), requestHandler=RequestHandler, allow_none=True, encoding="utf8") random_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") random_server.register_introspection_functions() random_server.register_instance(RandomServer()) server.add_dispatcher("/random", random_server) file_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") file_server.register_introspection_functions() file_server.register_instance(FileServer()) server.add_dispatcher("/fileserver", file_server) secret_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") secret_server.register_introspection_functions() secret_server.register_instance(SecretServer()) server.add_dispatcher("/secret_illuminati_world_domination_plans", secret_server) info_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") info_server.register_introspection_functions()
class WSGIXMLRPCApplication(object): """WSGI application to handle requests to the XMLRPC service. This WSGI application acts like the Python standard `SimpleXMLRPCServer` but processes WSGI requests instead and does not fiddle around with raw HTTP. The passed in `cache_dir` is used only if set. """ def __init__(self, cache_dir=None): # set up a dispatcher self.dispatcher = SimpleXMLRPCDispatcher( allow_none=True, encoding=None) self.dispatcher.register_function( self.convert_locally, 'convert_locally') self.dispatcher.register_function( self.get_cached, 'get_cached') self.dispatcher.register_introspection_functions() self.cache_dir = cache_dir def convert_locally(self, src_path, options): """Convert document in `path`. Expects a local path to the document to convert. The `options` are a dictionary of options as accepted by all converter components in this package. The cache (if set) will be updated. Returns path of converted document, a cache key and a dictionary of metadata. The cache key is ``None`` if no cache was used. """ result_path, cache_key, metadata = convert_doc( src_path, options, self.cache_dir) return result_path, cache_key, metadata def get_cached(self, cache_key): """Get a cached document. Retrieve the document representation stored under `cache_key` in cache if it exists. Returns `None` otherwise. """ client = Client(cache_dir=self.cache_dir) return client.get_cached(cache_key) @wsgify def __call__(self, req): """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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ if req.method != 'POST': return exc.HTTPBadRequest() try: data = req.environ['wsgi.input'].read(req.content_length) response = self.dispatcher._marshaled_dispatch( data, self.dispatcher._dispatch ) + '\n' except: # pragma: no cover # This should only happen if the module is buggy # internal error, report as HTTP server error return exc.HTTPServerError() else: # got a valid XML RPC response response = Response(response) response.content_type = 'text/xml' return response
class WSGIXMLRPCApplication(object): """WSGI application to handle requests to the XMLRPC service. This WSGI application acts like the Python standard `SimpleXMLRPCServer` but processes WSGI requests instead and does not fiddle around with raw HTTP. The passed in `cache_dir` is used only if set. """ def __init__(self, cache_dir=None): # set up a dispatcher self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) self.dispatcher.register_function(self.convert_locally, 'convert_locally') self.dispatcher.register_function(self.get_cached, 'get_cached') self.dispatcher.register_introspection_functions() self.cache_dir = cache_dir def convert_locally(self, src_path, options): """Convert document in `path`. Expects a local path to the document to convert. The `options` are a dictionary of options as accepted by all converter components in this package. The cache (if set) will be updated. Returns path of converted document, a cache key and a dictionary of metadata. The cache key is ``None`` if no cache was used. """ result_path, cache_key, metadata = convert_doc(src_path, options, self.cache_dir) return result_path, cache_key, metadata def get_cached(self, cache_key): """Get a cached document. Retrieve the document representation stored under `cache_key` in cache if it exists. Returns `None` otherwise. """ client = Client(cache_dir=self.cache_dir) return client.get_cached(cache_key) @wsgify def __call__(self, req): """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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ if req.method != 'POST': return exc.HTTPBadRequest() try: data = req.environ['wsgi.input'].read(req.content_length) response = self.dispatcher._marshaled_dispatch( data, self.dispatcher._dispatch) + b'\n' except: # pragma: no cover # This should only happen if the module is buggy # internal error, report as HTTP server error return exc.HTTPServerError() else: # got a valid XML RPC response response = Response(response) response.content_type = 'text/xml' return response
# Author(s): Michael Hrivnak <*****@*****.**> # Sean Myers <*****@*****.**> # Copyright 2008 American Research Institute, Inc. from SimpleXMLRPCServer import SimpleXMLRPCDispatcher from django.http import HttpResponse from pr_services.rpc.service import ServiceManagers import facade import settings import sys if sys.version_info[:2] == (2, 4): dispatcher = SimpleXMLRPCDispatcher() elif sys.version_info[:2] >= (2, 5): dispatcher = SimpleXMLRPCDispatcher(allow_none = True, encoding = 'utf-8') dispatcher.register_introspection_functions() dispatcher.register_multicall_functions() def gateway(request): response = HttpResponse() if len(request.POST): response = HttpResponse(mimetype="application/xml") # Cleaner to reinstantiate than to add seemingly useless else clause response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) elif settings.DEBUG: response.write("<b>This is an XML-RPC Service.</b><br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: <pre>%s</pre>" % (method, help))
# Author(s): Michael Hrivnak <*****@*****.**> # Sean Myers <*****@*****.**> # Copyright 2008 American Research Institute, Inc. from SimpleXMLRPCServer import SimpleXMLRPCDispatcher from django.http import HttpResponse from pr_services.rpc.service import ServiceManagers import facade import settings import sys if sys.version_info[:2] == (2, 4): dispatcher = SimpleXMLRPCDispatcher() elif sys.version_info[:2] >= (2, 5): dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding='utf-8') dispatcher.register_introspection_functions() dispatcher.register_multicall_functions() def gateway(request): response = HttpResponse() if len(request.POST): response = HttpResponse( mimetype="application/xml" ) # Cleaner to reinstantiate than to add seemingly useless else clause response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) elif settings.DEBUG: response.write("<b>This is an XML-RPC Service.</b><br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods()
class MyXMLRPCApp(object): """WSGI to XMLRPC callable. XMLRPC WSGI callable app. Args: instance: An instance of XMLRPC module. Callable args: environ: WSGI environment dictionary. start_response: WSGI response functor for sending HTTP headers. """ _MAX_CHUNK_SIZE = 10 * 1024 * 1024 def __init__(self, instance): """Creates XML RPC dispatcher.""" self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) self.dispatcher.register_introspection_functions() if instance is not None: self.RegisterInstance(instance) def __call__(self, environ, start_response): session = WSGISession(environ, start_response) if session.Method() != 'POST': return session.BadRequest() return self._XMLRPCCall(session) def RegisterInstance(self, instance): self.dispatcher.register_instance(instance) def _XMLRPCCall(self, session): """Dispatches request data body.""" mediator = SessionMediator(session, self.dispatcher) response_data = '' try: # Reading body in chunks to avoid straining (python bug #792570) size_remaining = session.ContentLength() chunks = [] while size_remaining > 0: chunk_size = min(self._MAX_CHUNK_SIZE, size_remaining) buf = session.Read(chunk_size) if not buf: break chunks.append(buf) size_remaining -= len(buf) data = ''.join(chunks) # Dispatching data response_data = mediator.MarshaledDispatch(data) except: # pylint: disable=W0702 return session.ServerError() else: # Sending valid XML RPC response data return session.Response('text/xml', response_data) finally: error_message = session['xmlrpc_exception'] error_message = (': %s' % error_message if error_message else '') logging.info('%s %s [%3f s, %d B in, %d B out]%s', session.RemoteAddress(), session['xmlrpc_method'], time.time() - session.time, len(data), len(response_data), error_message)