Advertisement
Guest User

Command abstraction

a guest
Jul 4th, 2010
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. class CommandError (Exception):
  2.     """Represents an error on command handling"""
  3.     pass
  4.  
  5. class Command (object):
  6.     """Command
  7.  
  8.    Represents a command executed from CLI or
  9.    the daemon.
  10.    """
  11.     _data = {}
  12.     def __init__(self, command, params=None):
  13.         """Constructor"""
  14.         self._data['command'] = command.lower()
  15.         if params is not None:
  16.             self._data['params'] = dict(params)
  17.         else:
  18.             self._data['params'] = {}
  19.  
  20.     def get_command(self):
  21.         """Returns the command name"""
  22.         return self._data['command']
  23.  
  24.     def __getattr__(self, attr):
  25.         return self._data[attr]
  26.  
  27.     def __setattr__(self, attr, value):
  28.         self._data[attr] = value
  29.         return self
  30.  
  31.    def __unicode__(self):
  32.        """Returns the name of the command"""
  33.        return self._data['command']
  34.  
  35.  
  36. class CommandHandler (object):
  37.     """Command handler
  38.  
  39.    Handles commands and parameters supplied
  40.    by users and makes the appropriate calls
  41.    to the API.
  42.    """
  43.     _api = None
  44.     def __init__ (self):
  45.         """Constructor"""
  46.         self._api = API()
  47.  
  48.     def handle (self, command):
  49.         """Handles a command and outputs the response"""
  50.         if not isinstance(command, Command):
  51.             raise CommandError("Invalid command. Expecting Command object")
  52.  
  53.         cmd = command.get_command()
  54.         if callable(getattr(self._api, cmd)):
  55.             pass
  56.         else:
  57.             raise CommandError("Invalid command %s" % cmd)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement