Esempio n. 1
0
 def _dispatch(self, method, params):
     func = None
     try:
         func = self.funcs[method]
     except KeyError:
         if self.instance is not None:
             if hasattr(self.instance, '_dispatch'):
                 return self.instance._dispatch(method, params)
             else:
                 try:
                     func = SimpleXMLRPCServer.resolve_dotted_attribute(
                         self.instance, method, True)
                 except AttributeError:
                     pass
     if func is not None:
         try:
             if type(params) is types.ListType:
                 response = func(*params)
             else:
                 response = func(**params)
             return response
         except TypeError:
             return Fault(-32602, 'Invalid parameters: ')
         except:
             err_lines = traceback.format_exc().splitlines()
             trace_string = '%s | %s' % (err_lines[-3], err_lines[-1])
             fault = jsonrpclib.Fault(-32603,
                                      'Server error: %s' % trace_string)
             return fault
     else:
         return Fault(-32601, 'Method %s not supported.' % method)
Esempio n. 2
0
 def _dispatch(self, method, params):
     func = None
     try:
         func = self.funcs[method]
     except KeyError:
         if self.instance is not None:
             if hasattr(self.instance, "_dispatch"):
                 return self.instance._dispatch(method, params)
             else:
                 try:
                     func = SimpleXMLRPCServer.resolve_dotted_attribute(self.instance, method, True)
                 except AttributeError:
                     pass
     if func is not None:
         try:
             if type(params) is types.ListType:
                 # MODIFIED to pass service method name as well
                 response = func(method, *params)
             else:
                 # MODIFIED to pass service method name as well
                 response = func(method, **params)
             return response
         except TypeError:
             return Fault(-32602, "Invalid parameters.")
         except:
             err_lines = traceback.format_exc().splitlines()
             trace_string = "%s | %s" % (err_lines[-3], err_lines[-1])
             fault = jsonrpclib.Fault(-32603, "Server error: %s" % trace_string)
             return fault
     else:
         return Fault(-32601, "Method %s not supported." % method)
Esempio n. 3
0
  def _dispatch(self, method, params, **kwargs):
    """Dispatch a rpc call to the appropriate method with parameters.

    This method is copied from SimpleXMLRPCServer but adds
    kwargs so that REST methods can receive keyword arguments
    rather than just list of parameters, which is all XMLRPC supports.

    Args:
      method: string, method name
      params: tuple, list of arguments
      kwargs: optional, dict of keyword arguments
    Returns:
      output from the called method
    Raises:
      Exception: if unsupported method is called
    """
    func = None
    try:
      func = self.funcs[method]
    except KeyError:
      if self.instance is not None:
        if hasattr(self.instance, '_dispatch'):
          return self.instance._dispatch(method, params, kwargs)
        else:
          try:
            func = SimpleXMLRPCServer.resolve_dotted_attribute(
                self.instance,
                method,
                self.allow_dotted_names)
          except AttributeError:
            pass
    if func is not None:
      return func(*params, **kwargs)
    else:
      raise Exception('method "%s" is not supported' % method)
Esempio n. 4
0
 def _dispatch(self, method, params):
     func = None
     try:
         func = self.funcs[method]
     except KeyError:
         if self.instance is not None:
             if hasattr(self.instance, '_dispatch'):
                 return self.instance._dispatch(method, params)
             else:
                 try:
                     func = SimpleXMLRPCServer.resolve_dotted_attribute(
                         self.instance,
                         method,
                         True
                         )
                 except AttributeError:
                     pass
     if func is not None:
         try:
             if type(params) is types.ListType:
                 response = func(*params)
             else:
                 response = func(**params)
             return response
         except TypeError:
             return Fault(-32602, 'Invalid parameters: ')
         except:
             err_lines = traceback.format_exc().splitlines()
             trace_string = '%s | %s' % (err_lines[-3], err_lines[-1])
             fault = jsonrpclib.Fault(-32603, 'Server error: %s' % 
                                      trace_string)
             return fault
     else:
         return Fault(-32601, 'Method %s not supported.' % method)
Esempio n. 5
0
    def _dispatch(self, method, params, **kwargs):
        """Dispatch a rpc call to the appropriate method with parameters.

    This method is copied from SimpleXMLRPCServer but adds
    kwargs so that REST methods can receive keyword arguments
    rather than just list of parameters, which is all XMLRPC supports.

    Args:
      method: string, method name
      params: tuple, list of arguments
      kwargs: optional, dict of keyword arguments
    Returns:
      output from the called method
    Raises:
      Exception: if unsupported method is called
    """
        func = None
        try:
            func = self.funcs[method]
        except KeyError:
            if self.instance is not None:
                if hasattr(self.instance, '_dispatch'):
                    return self.instance._dispatch(method, params, kwargs)
                else:
                    try:
                        func = SimpleXMLRPCServer.resolve_dotted_attribute(
                            self.instance, method, self.allow_dotted_names)
                    except AttributeError:
                        pass
        if func is not None:
            return func(*params, **kwargs)
        else:
            raise Exception('method "%s" is not supported' % method)
Esempio n. 6
0
    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 = SimpleXMLRPCServer.resolve_dotted_attribute(
                            self.instance,
                            method,
                            self.allow_dotted_names
                            )
                    except AttributeError:
                        pass

        if func is not None:
            try:
                # since we are using a keyword xmlrpc proxy this is sending
                # the info comes in form of args and kwargs
                # so params has 2 items, the first being a list or tuple
                # and the second a dictionary
                if len(params) == 2 and  isinstance(params[1],dict) and\
                ( isinstance(params[0],list) or isinstance(params[0],tuple) ) :
                    return func(*params[0], **params[1])
                else:
                    # this is the default way in case a normal xmlrpclib.ServerProxy is used
                    return func(*params)
            except Exception:
                # extended functionality to let the client have the full traceback
                msg = traceback.format_exc()
                raise xmlrpclib.Fault(1, msg)
        else:
            raise Exception('method "%s" is not supported' % method)
Esempio n. 7
0
    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 = SimpleXMLRPCServer.resolve_dotted_attribute(
                            self.instance,
                            method,
                            self.allow_dotted_names
                            )
                    except AttributeError:
                        pass

        if func is not None:
            try:
                # since we are using a keyword xmlrpc proxy this is sending
                # the info comes in form of args and kwargs
                # so params has 2 items, the first being a list or tuple
                # and the second a dictionary
                if len(params) == 2 and isinstance(params[1], dict) and\
                        (isinstance(params[0], list) or isinstance(params[-1], tuple)):
                    return func(*params[0], **params[1])
                else:
                    # this is the default way in case a normal xmlrpclib.ServerProxy is used
                    return func(*params)
            except Exception:
                # extended functionality to let the client have the full traceback
                msg = traceback.format_exc()
                raise xmlrpclib.Fault(1, msg)
        else:
            raise Exception('method "%s" is not supported' % method)
Esempio n. 8
0
    def test_dotted_attribute(self):
        # Raises an AttributeError because private methods are not allowed.
        self.assertRaises(AttributeError, SimpleXMLRPCServer.resolve_dotted_attribute, str, "__add")

        self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, "title"))
        # Get the test to run faster by sending a request with test_simple1.
        # This avoids waiting for the socket timeout.
        self.test_simple1()
    def test_dotted_attribute(self):
        # Raises an AttributeError because private methods are not allowed.
        self.assertRaises(AttributeError,
                          SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')

        self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
        # Get the test to run faster by sending a request with test_simple1.
        # This avoids waiting for the socket timeout.
        self.test_simple1()
Esempio n. 10
0
    def _dispatch(self, method, params):
        """
        Default method resolver and caller
        
        :param method: Name of the method to call
        :param params: List of arguments to give to the method
        :return: The result of the method
        """
        func = None
        try:
            # Try with registered methods
            func = self.funcs[method]

        except KeyError:
            if self.instance is not None:
                # Try with the registered instance
                if hasattr(self.instance, '_dispatch'):
                    # Instance has a custom dispatcher
                    return self.instance._dispatch(method, params)

                else:
                    # Resolve the method name in the instance
                    try:
                        func = xmlrpcserver.resolve_dotted_attribute(\
                                                self.instance, method, True)
                    except AttributeError:
                        # Unknown method
                        pass

        if func is not None:
            try:
                # Call the method
                if type(params) is utils.ListType:
                    return func(*params)

                else:
                    return func(**params)

            except TypeError as ex:
                # Maybe the parameters are wrong
                return Fault(-32602, 'Invalid parameters: {0}'.format(ex))

            except:
                # Method exception
                err_lines = traceback.format_exc().splitlines()
                trace_string = '{0} | {1}'.format(err_lines[-3], err_lines[-1])
                return Fault(-32603, 'Server error: {0}'.format(trace_string))

        else:
            # Unknown method
            return Fault(-32601, 'Method {0} not supported.'.format(method))
Esempio n. 11
0
    def my_dispatch(self, methodName, params, auth, client_addr):
        """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,
        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 '_' (except _dispatch) are considered
        private and will not be called.
        """
        kwdargs = {}
        func = None

        # check for a _dispatch method
        if (self.instance is not None) and hasattr(self.instance, '_dispatch'):
            return self.instance._dispatch(methodName, params, kwdargs,
                                           auth, client_addr)

        try:
            # check to see if a matching function has been registered
            func = self.funcs[methodName]

        except KeyError:
            if self.instance is not None:
                # call instance method directly
                try:
                    func = SimpleXMLRPCServer.resolve_dotted_attribute(
                        self.instance,
                        methodName,
                        self.allow_dotted_names
                        )
                except AttributeError:
                    pass

        if func is not None:
            return func(*params, **kwdargs)
        else:
            raise Error('method "%s" is not supported' % methodName)
Esempio n. 12
0
    def my_dispatch(self, methodName, params, auth, client_addr):
        """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,
        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 '_' (except _dispatch) are considered
        private and will not be called.
        """
        kwdargs = {}
        func = None

        # check for a _dispatch method
        if (self.instance is not None) and hasattr(self.instance, '_dispatch'):
            return self.instance._dispatch(methodName, params, kwdargs,
                                           auth, client_addr)

        try:
            # check to see if a matching function has been registered
            func = self.funcs[methodName]

        except KeyError:
            if self.instance is not None:
                # call instance method directly
                try:
                    func = SimpleXMLRPCServer.resolve_dotted_attribute(
                        self.instance,
                        methodName,
                        self.allow_dotted_names
                        )
                except AttributeError:
                    pass

        if func is not None:
            return func(*params, **kwdargs)
        else:
            raise Error('method "%s" is not supported' % methodName)
Esempio n. 13
0
 def get_handler(self, method):
     '''获取对应的方法的处理句柄
     '''
     func = None
     try:
         #先检查已经注册的函数
         func = self.funcs[method]
     except KeyError:
         if self.instance is not None:
             #检查已经注册的实例的成员函数
             try:
                 func = SimpleXMLRPCServer.resolve_dotted_attribute(
                     self.instance, method, self.allow_dotted_names)
             except AttributeError:
                 pass
     return func
Esempio n. 14
0
    def _dispatch(self, method, params):
        if self.server.instance is None:
            logging.error("Client without a server instance!")
            raise AskgodException("Internal server error.")

        # call instance method directly
        func = None
        try:
            func = SimpleXMLRPCServer.resolve_dotted_attribute(
                self.server.instance,
                method,
                self.server.allow_dotted_names)
        except Exception as e:
            logging.info("Failed to resolv '%s': %s" % (method, e))
            raise AskgodException("Unable to resolve method name.")

        if not func:
            logging.info("Function '%s' doesn't exist." % func)
            raise AskgodException("Invalid method name.")

        # Per connection data (address, DB connection, request)
        client = {}
        client['client_address'] = self.client_address[0]
        client['db_store'] = Store(self.server.database)
        client['request'] = self.request

        forwarded_address = self.headers.get("X-Forwarded-For", "")
        if forwarded_address:
            client['client_address'] = forwarded_address

        # Actually call the function
        try:
            retval = func(client, *params)
        except not AskgodException:
            logging.error(traceback.format_exc())
            raise AskgodException("Internal server error.")

        # Attempt to close the DB connection (if still there)
        try:
            client['db_store'].commit()
            client['db_store'].close()
        except:
            pass

        return retval