Example #1
0
class Server:
    def __init__(self, port):
        self.socket = zmq.Context().socket(zmq.REP)
        self.socket.bind("tcp://127.0.0.1:" + str(port))
        self.algo = Algo()
        self.stockHandler = self.algo.sdc
        self.sip = self.algo.sip
        self.should_shutdown = False

    def __try_communication(self):
        self.socket.send_string('{ Communication test : successful }')

    def run(self):
        try:
            while True:
                #  Wait for next request from client
                print("waiting for client input...")
                bytes = self.socket.recv()

                #  Do some 'work'
                #time.sleep(1)

                #  Send reply back to client
                message = bytes.decode('utf-8')
                print("MESSAGE: " + message)
                self.reply(json.loads(message))
                if (self.should_shutdown):
                    raise ShutdownException(
                        "server shutdown due to controller command")
                time.sleep(1)

        except Exception as e:
            if (type(e) == ShutdownException):
                print(
                    "******* Server shutting down due to controller command *******"
                )
            else:
                print("CAUGHT AN EXCEPTION, SHUTTING DOWN...")
                s.socket.__exit__()
                raise

    def reply(self, message):
        self.socket.send_string(self.handle(message))

    def __shouldExit(self):
        self.should_shutdown = True

    def __getHistorical(self, request, entry):
        #TODO: sort requests by stock and handle requests to same stock together (not sure if faster)
        a = self.stockHandler.getHistorical(request["symbol"],
                                            request["start"],
                                            request["end"])  # add reply
        return json.dumps(json.loads(str(a)))

    def __getRecommend(self, request, entry):
        self.replies[entry] = self.algo.getRecommend()

    def _getPredHistory(self, request, entry):
        self.replies[entry] = self.algo.getPredHistory()

    def __easySearch(self, request, entry):
        a = self.algo.getEasySearch(request["budget"])

        jsonObj = {}
        i = 0
        for stock_symbol, info in list(a.items()):
            if (len(info) == 0 or len(info.iloc[0]) != 9):
                continue
            d = {}
            valid = True
            for info_entry, value in info.to_dict().items():
                if (value[self.algo.sdc.lastUpdated] !=
                        value[self.algo.sdc.lastUpdated]):
                    valid = False
                    break
                d[info_entry] = value.popitem()[1]
            if (valid):
                jsonObj[i] = d  #jsonObj[stock_symbol] = d
                i += 1
        # pprint(jsonObj)
        # print(str(jsonObj)[5513:5533])
        # pprint(jsonObj)
        # pprint(jsonObj)
        return json.dumps(jsonObj)

    def __advancedSearch(self, request, entry):
        a = self.algo.getAdvSearch(request["budget"], request["companyType"],
                                   request["companyName"])
        jsonObj = {}
        i = 0
        for stock_symbol, info in list(a.items()):
            if (len(info) == 0 or len(info.iloc[0]) != 9):
                continue
            d = {}
            valid = True
            for info_entry, value in info.to_dict().items():
                if (value[self.algo.sdc.lastUpdated] !=
                        value[self.algo.sdc.lastUpdated]):
                    valid = False
                    break
                d[info_entry] = value.popitem()[1]
            if (valid):
                jsonObj[i] = d  # jsonObj[stock_symbol] = d
                i += 1
        # pprint(jsonObj)
        # print(str(jsonObj)[5513:5533])
        # pprint(jsonObj)
        # pprint(jsonObj)
        return json.dumps(jsonObj)

    def handle(self, message):
        print("Got message: ", end='')
        pprint(message)
        self.replies = {}
        #handle each request and append the replies dictionary with a reply. Exit when receiving an entry with "exit" value.
        for entry in message:
            # reply = []
            request = message[entry]
            action = request["action"]
            if (action == "exit"):
                return self.__shouldExit()
            elif (comp(action, "getRecommend")):
                return self.__getRecommend(request, entry)
            elif (comp(action, "getHistorical")):
                return self.__getHistorical(request, entry)
            elif (comp(action, "easySearch")):
                return self.__easySearch(request, entry)
            elif (comp(action, "advancedSearch")):
                return self.__advancedSearch(request, entry)
Example #2
0
class Server:
    def __init__(self, port):
        self.socket = zmq.Context().socket(zmq.REP)
        self.socket.bind("tcp://127.0.0.1:" + str(port))
        self.algo = Algo()
        self.stockHandler = StockHandler()
        self.should_shutdown = False

    def __try_communication(self):
        self.socket.send_string('{ Communication test : successful }')

    def run(self):
        try:
            while True:
                #  Wait for next request from client
                print("waiting for client input...")
                bytes = self.socket.recv()

                #  Do some 'work'
                #time.sleep(1)

                #  Send reply back to client
                message = bytes.decode('utf-8')
                self.reply(json.loads(message))
                if(self.should_shutdown):
                    raise ShutdownException("server shutdown due to controller command")

        except Exception as e:
            if (type(e) == ShutdownException):
                print("******* Server shutting down due to controller command *******")
            else:
                print("CAUGHT AN EXCEPTION, SHUTTING DOWN...")
                s.socket.__exit__()
                raise

    def reply(self, message):
        self.socket.send_json(self.handle(message))

    def __shouldExit(self):
        self.should_shutdown = True

    def __getHistorical(self, request, entry):
        #TODO: sort requests by stock and handle requests to same stock together (not sure if faster)
        self.replies[entry] = self.stockHandler.getHistorical(request["symbol"], request["start"], request["end"])  # add reply

    def __getRecommend(self, request, entry):
        self.replies[entry] = self.algo.getRecommend()

    def __easySearch(self, request, entry):
        self.replies[entry] = self.algo.getEasySearch(request["budget"])

    def __advancedSearch(self, request, entry):
        self.replies[entry] = self.algo.getAdvSearch(request["budget"], request["companyType"], request["companyName"])

    def handle(self, message):
        print("Got message: ")
        pprint(message)
        self.replies = {}
        #handle each request and append the replies dictionary with a reply. Exit when receiving an entry with "exit" value.
        for entry in message:
            request = message[entry]
            action = request["action"]
            if (action == "exit"):
                self.__shouldExit()
            elif(comp(action, "getRecommend")):
                self.__getRecommend(request, entry)
            elif(comp(action, "getHistorical")):
                self.__getHistorical(request, entry)
            elif(comp(action, "easySearch")):
                self.__easySearch(request, entry)
            elif (comp(action, "advancedSearch")):
                self.__advancedSearch(request, entry)
        return self.replies