def tsend(self, string): s = self.s try: return s.sendall(string) except (socket.error, AttributeError) as msg: useful.error("tsend filed.", msg) return False
def getFile(self, path): try: with open(path) as f: data = f.read() return data except Exception as msg: useful.error("Unable to get file.", msg) return
def loadPreloadLits(): try: preload_list = [] with open(CACHE_CONFIG_PATH) as f: data = f.read() data = json.loads(data) for pre_file in data["PRELOAD_FILES"]: preload_list.append(pre_file) return preload_list except Exception as e: useful.error("Preload filed.", e)
def getPreloadFiles(file_list): try: preload_dict = {} for pre_file in file_list: path = "{}/{}".format(PUBLIC_WWW_DIR, pre_file) with open(path, "rb") as f: data = f.read() preload_dict.update({pre_file: data}) return preload_dict except Exception as e: useful.error("Preload filed.", e)
def openTCP(self, host, port, slots): addr = (host, port) try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(slots) s.settimeout(None) return s except socket.error as msg: useful.error("TCP socket filed.", msg) return False
def loadConfigFiles(): conf = {} try: for section in LIST_OF_SECTIONS: path = "{}/{}".format(CONFIG_DIRECTORY, section) name, _ = os.path.splitext(section) with open(path, "r") as f: data = f.read() data = json.loads(data) conf.update({name: data}) except Exception as e: useful.error("Config loading filed.", e) return conf
def urecv(self, string): s = self.s data = "" rest = "" while str(data).find(string) == -1: try: rest = str(s.recv(1)) if len(rest) == 0: raise BadRequest() except (socket.error, AttributeError) as msg: useful.error("urecv filed.", msg) return False data += rest return str(data)
def run(self, s=None): if s is None and self.s: s = self.s else: useful.error("TCP socket filed") while True: try: conn, addr = s.accept() conn.setblocking(1) useful.alert("New connection established: {}".format(addr)) th = TCP_HTTP_HANDLER(conn, self.cfg, self.preload) th.deamon = False th.start() except socket.error as msg: if msg.errno == errno.ENOTCONN: continue useful.error("Accept filed.", msg) return False except AttributeError: useful.error("Accept filed.", msg) return False except KeyboardInterrupt: sys.exit()
def parseCfg(self, config): try: for section, data in config.items(): globals()[section.upper()] = data except ValueError as e: useful.error("Configs loading error.", e)