예제 #1
0
파일: command.py 프로젝트: ElDeveloper/pyqi
class Command(object):
    """Base class for ``Command``

    A ``Command`` is interface agnostic, knows how to run itself and knows 
    about the arguments that it can take (via ``Parameters``).

    """
    BriefDescription = "" # 1 sentence description
    LongDescription = """""" # longer, more detailed description
    CommandIns = ParameterCollection([])
    CommandOuts = ParameterCollection([])

    def __init__(self, **kwargs):
        """ """
        self._logger = NullLogger()

    def __call__(self, **kwargs):
        """Safely execute a ``Command``"""
        self_str = str(self.__class__)
        self._logger.info('Starting command: %s' % self_str)
        
        self._validate_kwargs(kwargs)
        self._set_defaults(kwargs)

        try:
            result = self.run(**kwargs)
        except Exception, e:
            self._logger.fatal('Error executing command: %s' % self_str)
            raise e
        else:
예제 #2
0
파일: command.py 프로젝트: ebolyen/pyqi
 def __init__(self, **kwargs):
     """ """
     self._logger = NullLogger()
예제 #3
0
파일: command.py 프로젝트: ebolyen/pyqi
class Command(object):
    """Base class for ``Command``

    A ``Command`` is interface agnostic, knows how to run itself and knows 
    about the arguments that it can take (via ``Parameters``).

    """
    BriefDescription = "" # 1 sentence description
    LongDescription = """""" # longer, more detailed description
    CommandIns = ParameterCollection([])
    CommandOuts = ParameterCollection([])

    def __init__(self, **kwargs):
        """ """
        self._logger = NullLogger()

    def __call__(self, **kwargs):
        """Safely execute a ``Command``"""
        self_str = str(self.__class__)
        self._logger.info('Starting command: %s' % self_str)
        
        self._validate_kwargs(kwargs)
        self._set_defaults(kwargs)

        try:
            result = self.run(**kwargs)
        except Exception:
            self._logger.fatal('Error executing command: %s' % self_str)
            raise
        else:
            self._logger.info('Completed command: %s' % self_str)

        # verify the result type
        if not isinstance(result, dict):
            self._logger.fatal('Unsupported result return type for command: '
                               '%s' % self_str)
            raise InvalidReturnTypeError("Unsupported result return type. "
                                         "Results must be stored in a "
                                         "dictionary.")

        self._validate_result(result)

        return result

    def _validate_kwargs(self, kwargs):
        """Validate input kwargs prior to executing a ``Command``
        
        This method can be overridden by subclasses. The baseclass defines only
        a basic validation.
        """
        self_str = str(self.__class__)

        # check required parameters
        for p in self.CommandIns.values():
            if p.Required and p.Name not in kwargs:
                err_msg = 'Missing required CommandIn %s in %s' % (p.Name, 
                                                                   self_str)
                self._logger.fatal(err_msg)
                raise MissingParameterError(err_msg)

            if p.Name in kwargs and p.ValidateValue:
                if not p.ValidateValue(kwargs[p.Name]):
                    err_msg = "CommandIn %s cannot take value %s in %s" % \
                                (p.Name, kwargs[p.Name], self_str)
                    self._logger.fatal(err_msg)
                    raise ValueError(err_msg)

        # make sure we only have things we expect
        for opt in kwargs:
            if opt not in self.CommandIns:
                err_msg = 'Unknown CommandIn %s in %s' % (opt, self_str)
                self._logger.fatal(err_msg)
                raise UnknownParameterError(err_msg)
    
    def _validate_result(self, result):
        """Validate the result from a ``Command.run``"""
        self_str = str(self.__class__)

        for p in self.CommandOuts.values():
            if p.Name not in result:
                err_msg = "CommandOut %s not in %s" % (p.Name, self_str)
                self._logger.fatal(err_msg)
                raise UnknownParameterError(err_msg)
        for k in result:
            if k not in self.CommandOuts:
                err_msg = "Unknown CommandOut %s in %s" % (k, self_str)
                self._logger.fatal(err_msg)
                raise UnknownParameterError(err_msg)

    def _set_defaults(self, kwargs):
        """Set defaults for optional parameters"""
        for p in self.CommandIns.values():
            if not p.Required and p.Name not in kwargs:
                kwargs[p.Name] = p.Default

    def run(self, **kwargs):
        """Exexcute a ``Command``
        
        A ``Command`` must accept **kwargs to run, and must return a ``dict``
        as a result.
        """
        raise NotImplementedError("All subclasses must implement run.")
예제 #4
0
파일: command.py 프로젝트: biocore/pyqi
 def __init__(self, **kwargs):
     """ """
     self._logger = NullLogger()
예제 #5
0
파일: command.py 프로젝트: biocore/pyqi
class Command(object):
    """Base class for ``Command``

    A ``Command`` is interface agnostic, knows how to run itself and knows
    about the arguments that it can take (via ``Parameters``).

    """
    BriefDescription = ""  # 1 sentence description
    LongDescription = """"""  # longer, more detailed description
    CommandIns = ParameterCollection([])
    CommandOuts = ParameterCollection([])

    def __init__(self, **kwargs):
        """ """
        self._logger = NullLogger()

    def __call__(self, **kwargs):
        """Safely execute a ``Command``"""
        self_str = str(self.__class__)
        self._logger.info('Starting command: %s' % self_str)

        self._validate_kwargs(kwargs)
        self._set_defaults(kwargs)

        try:
            result = self.run(**kwargs)
        except Exception:
            self._logger.fatal('Error executing command: %s' % self_str)
            raise
        else:
            self._logger.info('Completed command: %s' % self_str)

        # verify the result type
        if not isinstance(result, dict):
            self._logger.fatal('Unsupported result return type for command: '
                               '%s' % self_str)
            raise InvalidReturnTypeError("Unsupported result return type. "
                                         "Results must be stored in a "
                                         "dictionary.")

        self._validate_result(result)

        return result

    def _validate_kwargs(self, kwargs):
        """Validate input kwargs prior to executing a ``Command``

        This method can be overridden by subclasses. The baseclass defines only
        a basic validation.
        """
        self_str = str(self.__class__)

        # check required parameters
        for p in self.CommandIns.values():
            if p.Required and p.Name not in kwargs:
                err_msg = 'Missing required CommandIn %s in %s' % (p.Name,
                                                                   self_str)
                self._logger.fatal(err_msg)
                raise MissingParameterError(err_msg)

            if p.Name in kwargs and p.ValidateValue:
                if not p.ValidateValue(kwargs[p.Name]):
                    err_msg = "CommandIn %s cannot take value %s in %s" % \
                                (p.Name, kwargs[p.Name], self_str)
                    self._logger.fatal(err_msg)
                    raise ValueError(err_msg)

        # make sure we only have things we expect
        for opt in kwargs:
            if opt not in self.CommandIns:
                err_msg = 'Unknown CommandIn %s in %s' % (opt, self_str)
                self._logger.fatal(err_msg)
                raise UnknownParameterError(err_msg)

    def _validate_result(self, result):
        """Validate the result from a ``Command.run``"""
        self_str = str(self.__class__)

        for p in self.CommandOuts.values():
            if p.Name not in result:
                err_msg = "CommandOut %s not in %s" % (p.Name, self_str)
                self._logger.fatal(err_msg)
                raise UnknownParameterError(err_msg)
        for k in result:
            if k not in self.CommandOuts:
                err_msg = "Unknown CommandOut %s in %s" % (k, self_str)
                self._logger.fatal(err_msg)
                raise UnknownParameterError(err_msg)

    def _set_defaults(self, kwargs):
        """Set defaults for optional parameters"""
        for p in self.CommandIns.values():
            if not p.Required and p.Name not in kwargs:
                kwargs[p.Name] = p.Default

    def run(self, **kwargs):
        """Exexcute a ``Command``

        A ``Command`` must accept **kwargs to run, and must return a ``dict``
        as a result.
        """
        raise NotImplementedError("All subclasses must implement run.")