def json_loads_byteified(json_text): """ Package json loads with hook. """ try: result = _byteify(json.loads(json_text, object_hook=_byteify), ignore_dicts=True) except Exception as e: TheLogger.error("Json load failed: %s" % str(e)) return None return result
def json_file_to_pyData(jsonFile): """ Convert json file to python data. """ if not is_file_existing(jsonFile): TheLogger.error("Json file is not found: %s" % jsonFile) return None with codecs.open(jsonFile, encoding="utf-8") as f: try: return json_load_byteified(f) except Exception as e: return None
def get_response_pattern(): """ Get response data. """ responsePattern = {} try: responsePattern = json_file_to_pyData(pathRespPatternFile) if not responsePattern: responsePattern = {} TheLogger.debug("Current response pattern: \n" + \ json_dumps(responsePattern)) except Exception as e: TheLogger.error(str(e)) return responsePattern
def start(serverHost, serverPort): """ Start HTTP server. """ if not serverHost or not serverPort: TheLogger.error("Set server host and port.") exit(10) if not is_port_idle(serverPort): TheLogger.error("Port {} is in use.".format(serverPort)) exit(11) TheLogger.info("Start HTTP server with %s:%s..." % (serverHost, serverPort)) httpServer = HttpServer(serverHost, serverPort) httpServer.start()
def set_response_pattern(pathRespPatternFileIn, flagAddData): """ Set response data. """ try: responsePatternIn = json_file_to_pyData(pathRespPatternFileIn) TheLogger.debug("Input response pattern: \n" + \ json_dumps(responsePatternIn)) responsePattern = {} if flagAddData: responsePattern = get_response_pattern() responsePattern.update(**responsePatternIn) TheLogger.debug("Incomming response pattern: \n" + \ json_dumps(responsePattern)) pyData_to_json_file(responsePattern, pathRespPatternFile) except Exception as e: TheLogger.error(str(e))
except Exception as e: TheLogger.error(str(e)) if __name__ == "__main__": """ Main enter. """ pathTempDataDir = path_join(PATH_ROOT, "temp") pathRespPatternFile = path_join(pathTempDataDir, "response_pattern.json") make_dir(pathTempDataDir) TheLogger.init(pathTempDataDir, "server.log") mode = sys.argv[1] if mode == "start": serverHost = "127.0.0.1" try: serverPort = int(sys.argv[2]) except Exception as e: print("Error: specify port correctly.") start(serverHost, serverPort) elif mode == "set_response_pattern": pathRespPatternFileIn = sys.argv[2] flagAddData = bool(int(sys.argv[3])) set_response_pattern(pathRespPatternFileIn, flagAddData) elif mode == "get_response_pattern": get_response_pattern() else: TheLogger.error("Unknown parameter {}.".format(mode))