Ejemplo n.º 1
0
class ServerThread(threading.Thread):
    """Responds to the request sent from a Todo client."""

    def __init__(self, client, config):
        """Initializes database and stores the client for the thread to use.

        Args:
            config: dictionary containing login information for MySQL and the
            default tag if it was present in the config file or as an argument.
        """
        super(ServerThread, self).__init__()
        self.__client = client

        if 'default_tag' in config:
            default_tag = config['default_tag']
            del config['default_tag']
        else:
            default_tag = Database.DEFAULT_TAG
        self.__db = Database(default_tag)
        if self.__db.connect(**config) == Database.CANT_CONNECT:
            print 'MySQL error: incorrect credentials or server is not running'
            sys.exit(1)

    def run(self):
        """Processes and responds to a Todo client request."""
        json_message = self.__client.receive()
        message = json.loads(json_message)
        response = []
        try:
            for action in message:
                operation = Network.OPERATIONS[int(action[0])]
                part = [action[0], getattr(self.__db, operation)(*action[1])]
                if not isinstance(part[1], int):
                    part.insert(1, Database.DATA)
                response.append(part)
        except IndexError:
            print "network error: Invalid JSON client request"
            sys.exit(1)
        print response
        date_handler = lambda obj: obj.strftime('%m-%d-%Y') \
                if isinstance(obj, datetime.date) else None
        print json.dumps(response, default=date_handler)
        self.__client.send(json.dumps(response, default=date_handler))
        self.__client.close()
Ejemplo n.º 2
0
    def __init__(self, client, config):
        """Initializes database and stores the client for the thread to use.

        Args:
            config: dictionary containing login information for MySQL and the
            default tag if it was present in the config file or as an argument.
        """
        super(ServerThread, self).__init__()
        self.__client = client

        if 'default_tag' in config:
            default_tag = config['default_tag']
            del config['default_tag']
        else:
            default_tag = Database.DEFAULT_TAG
        self.__db = Database(default_tag)
        if self.__db.connect(**config) == Database.CANT_CONNECT:
            print 'MySQL error: incorrect credentials or server is not running'
            sys.exit(1)