def get(self, *args, **kargs): dict_arguments = { k: self.request.arguments.get(k)[0].decode('utf-8') for k in self.request.arguments } self.interfaceConfig = config(self._projectdata_dir_gui) if "authorization" in self.interfaceConfig: authorization = self.interfaceConfig["authorization"] else: authorization = os.urandom(12).hex() self.interfaceConfig = config(self._projectdata_dir_gui, {"authorization": authorization}) if args[0] == "test_list": msg = 'Test List' self.set_status(200) return self.write({ "status": "OK", "message": msg, "test_list": test_list, 'i18n': { "message": self.T(msg) } }) elif args[0] == "requeriment_list": msg = 'Test Requeriments' self.set_status(200) return self.write({ "status": "OK", "message": msg, "requeriment_list": requeriments, 'i18n': { "message": self.T(msg) } })
def open(self): print("WebSocket opened") self.write_message( u"______ _ _ ______ _ _ ___ " ) self.write_message( u"| ___ \| | | | | ___ \| | | | / _ \ " ) self.write_message( u"| |_/ /| |__ __ _ _ __ | |_ ___ _ __ | |_/ /| | | |/ /_\ \\" ) self.write_message( u"| __/ | '_ \ / _` || '_ \ | __| / _ \| '__|| __/ | |/\| || _ |" ) self.write_message( u"| | | | | || (_| || | | || |_ | __/| | | | \ /\ /| | | |" ) self.write_message( u"\_| |_| |_| \__,_||_| |_| \__| \___||_| \_| \/ \/ \_| |_/" ) self.interfaceConfig = config(self._projectdata_dir_gui) if "authorization" in self.interfaceConfig: self.admin_authorization = self.interfaceConfig["authorization"] else: self.admin_authorization = os.urandom(12).hex() self.interfaceConfig = config( self._projectdata_dir_gui, {"authorization": self.admin_authorization}) self.connections.add(self)
def main(): args = parser.parse_args() if args.gui: start() elif args.compile_and_server_last_project or args.server_last_project: if 'last_application' in CONFIG: configProject = config(CONFIG['last_application']) projectPath = CONFIG['last_application'] if args.compile_and_server_last_project: try: Compiler(projectPath).compile() except Exception as e: traceback.print_tb(e.__traceback__) print("API Server running in http://{0}:{1}".format( configProject['API_SERVER']['host'], configProject['API_SERVER']['port'])) print("APP Server running in http://{0}:{1}".format( configProject['APP_SERVER']['host'], configProject['APP_SERVER']['port'])) try: print("Press CTRL+C to stop server!") config(CWD, {'last_application': configProject['PATH']['project']}) start_server(projectPath) except KeyboardInterrupt: target = os.path.abspath(os.path.join("..", "server.py")) for p in psutil.process_iter(): cmd_line = None try: cmd_line = p.cmdline() except Exception: pass if cmd_line: if ENV_PYTHON == cmd_line[0]: if os.path.normpath(target) == cmd_line[-1]: p.terminate() CLEAR_CONSOLE() input("Server Stoped""! Press <enter> key to exit.") CLEAR_CONSOLE() except Exception as e: traceback.print_tb(e.__traceback__) input("Server error, check the log file to learn more. Press <enter> key to exit.") CLEAR_CONSOLE() else: print("Try --cli or -c arguments") return True
def open_window_projects(self): print(self.CONFIG) if self.app_folder_input.get(): self.CONFIG = config(self._projectdata_dir_gui, {"projects_folder": os.path.normpath(self.projects_folder)}) self.tkInstance.destroy() # if not self.ProjectsPWA: # tkInstance = tk.Toplevel(self.tkInstance) # self.ProjectsPWA = ProjectsPWA(tkInstance, self) # else: # self.ProjectsPWA.tkInstance.destroy() # tkInstance = tk.Toplevel(self.tkInstance) # self.ProjectsPWA = ProjectsPWA(tkInstance, self) pass
def test4_config(self): if os.path.exists("config.json"): os.remove("config.json") if os.path.exists("cfg.json"): os.remove("cfg.json") if os.path.exists("test_folder"): import glob c = glob.glob(os.path.join("test_folder", "*")) for x in c: os.remove(x) os.removedirs("test_folder") self.assertEqual(os.path.exists("config.json"), False) self.assertEqual(os.path.exists("cfg.json"), False) self.assertEqual(os.path.exists("test_folder"), False) config("test_folder") self.assertEqual(os.path.exists("test_folder.json"), True) os.remove("test_folder.json") self.assertEqual(os.path.exists("test_folder.json"), False) config(os.path.join("test_folder", "cfg.json")) self.assertEquals( os.path.exists(os.path.join("test_folder", "cfg.json")), True) config(os.path.join("test_folder", "cfg")) self.assertEquals( os.path.exists(os.path.join("test_folder", "cfg.json")), True) config(os.path.join("test_folder", "cfgij")) self.assertEquals( os.path.exists(os.path.join("test_folder", "cfgij.json")), True) config(os.path.join("test_folder")) self.assertEquals( os.path.exists(os.path.join("test_folder", "config.json")), True) content = {"teste": "one"} change = {"teste": "two", "new": "one"} acumulate = {"teste": "two", "new": "one", "just": "three"} res = config(os.path.join("test_folder"), content) self.assertEquals(res, content) res = config(os.path.join("test_folder"), change) self.assertEquals(res, change) res = config(os.path.join("test_folder"), {"just": "three"}) self.assertEquals(res, acumulate) res = config(os.path.join("test_folder"), {"just": "three"}, rewrite=True) self.assertEquals(res, {"just": "three"})
def run(self, project_path, compile=False, thread=False): temp_dir = os.path.join(project_path, "temp") ppwa_version_file = os.path.join(project_path, "temp", 'ppwa_version') ppwa_version = None project_version = "0.0.1" if os.path.isfile(ppwa_version_file): with open(ppwa_version_file, 'r', encoding="utf-8") as f: ppwa_version = f.read() elif os.path.isdir(temp_dir): ppwa_version = PHANTERPWA_VERSION with open(ppwa_version_file, 'w', encoding="utf-8") as f: f.write(ppwa_version) # majors_version = majors_version_cfg = "0.0" if os.path.isfile(os.path.join(project_path, 'project.ini')): self._ini_project.read(os.path.join(project_path, 'project.ini'), encoding='utf-8') project_version = self._ini_project["PROJECT"].get( "version", "0.0.1") # if version_regex.match(project_version): # majors_version = ".".join(project_version.split(".")[0:2]) if os.path.isfile(os.path.join(project_path, "config.json")): cfg_ini = config(os.path.join(project_path, "config.json")) else: cfg_ini = configer.ProjectConfig(project_path) project_version_cfg = cfg_ini["PROJECT"]["version"] # project_version_cfg = cfg_ini["PROJECT"]["version"] # if version_regex.match(project_version_cfg): # majors_version_cfg = ".".join(project_version_cfg.split(".")[0:2]) reset_compilation = False cfg = configer.ProjectConfig(project_path) if str(project_version).strip() != str(project_version_cfg).strip(): reset_compilation = True # if majors_version != majors_version_cfg: # reset_compilation = True # new_version = ".".join([majors_version, str(0)]) # elif project_version_cfg != project_version: # new_version = ".".join([majors_version, str(cfg_ini["PROJECT"]['compilation'])]) # else: # new_version = project_version # if compile or str(ppwa_version).strip() != str(PHANTERPWA_VERSION).strip(): # new_version = ".".join([majors_version, str(cfg_ini["PROJECT"]['compilation'])]) # with open(os.path.join(project_path, 'project.ini'), 'w', encoding="utf-8") as configfile: # self._ini_project["PROJECT"]["version"] = new_version # self._ini_project.write(configfile) if compile: c = compiler.Compiler(project_path, reset_compilation=reset_compilation) c.compile() else: f_comp = False if str(project_version).strip() != str( project_version_cfg).strip(): f_comp = True print("Project version change:", str(project_version_cfg).strip(), "-->", str(project_version).strip()) if str(ppwa_version).strip() != str(PHANTERPWA_VERSION).strip(): f_comp = True print("PhanterPWA version change:", str(ppwa_version).strip(), "-->", str(PHANTERPWA_VERSION).strip()) if f_comp: c = compiler.Compiler(project_path, reset_compilation=reset_compilation) c.compile() with open(ppwa_version_file, 'w', encoding="utf-8") as f: f.write(PHANTERPWA_VERSION) target = os.path.normpath( os.path.join(self.path_phanterpwa, "server.py {0}".format(project_path))) self.stop(project_path) command = " ".join([self.env_python, "-X utf8", target]) print() print("=" * 79) print("Starting server..........") if cfg['BACKEND']: print('BACKEND') for a in cfg['BACKEND']: print(" ", a) print(" HOST:", cfg['BACKEND'][a]['host']) print(" PORT:", cfg['BACKEND'][a]['port']) print() if cfg['FRONTEND']: print('FRONTEND') for a in cfg['FRONTEND']: print(" ", a) print(" HOST:", cfg['FRONTEND'][a]['host']) print(" PORT:", cfg['FRONTEND'][a]['port']) print() with open(os.path.join(self.path_phanterpwa, "samples", "art"), "r") as f: print(f.read()) print() print("=" * 79) if thread: t = threading.Thread(target=lambda: subprocess.call( command, cwd=project_path, shell=True)) t.start() return t else: try: subprocess.call(command, cwd=project_path, shell=True) except KeyboardInterrupt: self.stop(project_path)
def get(self, *args, **kargs): dict_arguments = { k: self.request.arguments.get(k)[0].decode('utf-8') for k in self.request.arguments } self.interfaceConfig = config(self._projectdata_dir_gui) if "authorization" in self.interfaceConfig: authorization = self.interfaceConfig["authorization"] else: authorization = os.urandom(12).hex() self.interfaceConfig = config(self._projectdata_dir_gui, {"authorization": authorization}) enviroment = { "python_executable": ENV_PYTHON, "python_path": ENV_PATH, "python_version": PY_VERSION, "phanterpwa_version": phanterpwa.__version__, "projects_folder": None } if args and args[0]: self._projects_path = self.interfaceConfig["projects_folder"] running = ProjectRunner() its_running = running.check( os.path.join(self._projects_path, args[0])) if os.path.isfile( os.path.join(self._projects_path, args[0], "config.json")): config_project = ProjectConfig( os.path.join(self._projects_path, args[0], "config.json")) msg = 'Project Found' self.set_status(200) return self.write({ "status": "OK", "message": msg, 'i18n': { "message": self.T(msg) }, "config": config_project.config, "running": its_running }) else: msg = 'Project not Found' self.set_status(400) return self.write({ "status": "Bad Request", "message": msg, 'i18n': { "message": self.T(msg) } }) else: if "projects_folder" in self.interfaceConfig: self._projects_path = self.interfaceConfig["projects_folder"] self.Projects = ProjectsList(self._projects_path) msg = "Application list" enviroment['projects_folder'] = self._projects_path running = ProjectRunner() self.set_status(200) return self.write({ "status": "OK", "message": msg, 'i18n': { "message": self.T(msg) }, "projects_list": [[ x[0], x[1], "running" if x[1] in running.projects else "stopped", ProjectConfig(os.path.join( x[1], "config.json"))['PROJECT']['baseport'] ] for x in self.Projects.projects_list], "authorization": authorization, "enviroment": enviroment, }) else: msg = "Get project list" self.set_status(202) self.write({ "status": "Accepted", "message": msg, "authorization": authorization, "enviroment": enviroment, 'i18n': { "message": self.T(msg) } })
def on_message(self, message): if message.startswith("{"): msg = None try: json_message = json.loads(message) except Exception as e: return self.write_message( json.dumps({ "status": 400, "error": "SyntaxError", "message": "The message must be json type." })) else: cmd = json_message["command"] if "authorization" in json_message and json_message["authorization"] == self.admin_authorization and\ "command" in json_message: if cmd == "change_project_folder": current_path = self.interfaceConfig["projects_folder"] ProjectsFolderTk() self.interfaceConfig = config( self._projectdata_dir_gui) if current_path == self.interfaceConfig[ "projects_folder"]: return self.write_message( json.dumps({ "status": 202, "message": "The path not changed.", "command": cmd })) else: return self.write_message( json.dumps({ "status": 200, "message": "Changed.", "command": cmd })) elif cmd == "requeriments_phanterpwa": for x in check_requeriments(): self.write_message({ "status": 206, "check": x[0], "result": x[1], "message": "Pip requeriment \"{0}\" checked".format(x[0]), "command": cmd }) self.write_message({ "status": 200, "message": "Pip requeriment finished.", "command": cmd }) elif cmd == "test_phanterpwa": suite = unittest.TestLoader().loadTestsFromModule( test_cli) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_cli", "result": test_exit_code, "message": "Test cli", "command": cmd }) suite = unittest.TestLoader().loadTestsFromModule( test_components_preloaders) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_components_preloaders", "result": test_exit_code, "message": "Test Proloaders", "command": cmd }) suite = unittest.TestLoader().loadTestsFromModule( test_helpers) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_helpers", "result": test_exit_code, "message": "Test helpers", "command": cmd }) suite = unittest.TestLoader().loadTestsFromModule( test_i18n) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_i18n", "result": test_exit_code, "message": "Test i18n", "command": cmd }) suite = unittest.TestLoader().loadTestsFromModule( test_reversexml) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_reversexml", "result": test_exit_code, "message": "Test reversexml", "command": cmd }) suite = unittest.TestLoader().loadTestsFromModule( test_tools) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_tools", "result": test_exit_code, "message": "Test tools", "command": cmd }) suite = unittest.TestLoader().loadTestsFromModule( test_configer) result = unittest.TextTestRunner( verbosity=2).run(suite) test_exit_code = bool(int(not result.wasSuccessful())) self.write_message({ "status": 206, "test": "test_configer", "result": test_exit_code, "message": "Test configer", "command": cmd }) self.write_message({ "status": 200, "message": "Test Finished", "command": cmd }) elif cmd == "compile": _project_path = json_message["project_path"] _application = json_message["application"] c = Compiler(_project_path) has_error = False for x in c.compile_by_step(_application): if not x[1]: has_error = True self.write_message({ "status": 206, "project_path": _project_path, "message": x, "command": cmd }) return self.write_message({ "status": 200 if not has_error else 202, "project_path": _project_path, "message": "Compile complete!" if not has_error else "Has error(s) on compilation", "command": cmd }) elif cmd == "run" or cmd == "stop" or cmd == "check" or cmd == "stop_all" or cmd == "check_all": _project_path = json_message["project_path"] R = ProjectRunner() if cmd == "run": R.run(_project_path, thread=True, compile=True) elif cmd == "stop": R.stop(_project_path) p = [x for x in R.projects.keys()] if p: r = { 'status': 200, 'message': 'Projects running', 'command': cmd, 'project_running': p } return self.write_message(json.dumps(r)) else: return self.write_message({ 'status': 202, 'message': 'All stopped!', 'command': cmd }) else: return self.write_message( json.dumps({ "status": 401, "error": "Unauthorized", "message": "Authorization not found.", "command": cmd }))
def get(self, *args, **kargs): dict_arguments = { k: self.request.arguments.get(k)[0].decode('utf-8') for k in self.request.arguments } self.interfaceConfig = config(self._projectdata_dir_gui) if "authorization" in self.interfaceConfig: authorization = self.interfaceConfig["authorization"] else: authorization = os.urandom(12).hex() self.interfaceConfig = config(self._projectdata_dir_gui, {"authorization": authorization}) enviroment = { "python_executable": ENV_PYTHON, "python_path": ENV_PATH, "python_version": PY_VERSION, "phanterpwa_version": phanterpwa.__version__, "projects_folder": None } if args and args[0]: self._projects_path = self.interfaceConfig["projects_folder"] running = ProjectRunner() its_running = running.check( os.path.join(self._projects_path, args[0])) if os.path.isfile( os.path.join(self._projects_path, args[0], "config.json")): config_project = ProjectConfig( os.path.join(self._projects_path, args[0], "config.json")) project_ini = config_project.project_ini api_ini = config_project.backend_ini secret_ini = config_project.frontend_secret_ini secret_ini_api = config_project.backend_secret_ini project_dict = {} api_dict = {} secret_dict = {} secret_dict_api = {'API': {}} for x in project_ini.sections(): if x not in project_dict: project_dict[x] = {} for k in project_ini.items(x): v = k[1] if v.isdigit(): project_dict[x][k[0]] = int(v) elif v.lower() == "false": project_dict[x][k[0]] = False elif v.lower() == "true": project_dict[x][k[0]] = True else: project_dict[x][k[0]] = v for x in api_ini.sections(): if x not in api_dict: api_dict[x] = {} for k in api_ini.items(x): v = k[1] if v.isdigit(): api_dict[x][k[0]] = int(v) elif v.lower() == "false": api_dict[x][k[0]] = False elif v.lower() == "true": api_dict[x][k[0]] = True else: api_dict[x][k[0]] = v for x in secret_ini.sections(): if x not in secret_dict: secret_dict[x] = {} for k in secret_ini.items(x): v = k[1] if v.isdigit(): secret_dict[x][k[0]] = int(v) elif v.lower() == "false": secret_dict[x][k[0]] = False elif v.lower() == "true": secret_dict[x][k[0]] = True else: secret_dict[x][k[0]] = v for k in secret_ini_api.items('API'): v = k[1] if v.isdigit(): secret_dict_api['API'][k[0]] = int(v) elif v.lower() == "false": secret_dict_api['API'][k[0]] = False elif v.lower() == "true": secret_dict_api['API'][k[0]] = True else: secret_dict_api['API'][k[0]] = v for y in secret_dict: for a in secret_dict[y]: if y not in project_dict: project_dict[y] = {} project_dict[y][a] = secret_dict[y][a] for y in secret_dict_api: for a in secret_dict_api[y]: if y not in api_dict: api_dict[y] = {} api_dict[y][a] = secret_dict_api[y][a] msg = 'Project Found' self.set_status(200) return self.write({ "status": "OK", "message": msg, 'i18n': { "message": self.T(msg) }, "project_config": project_dict, "api_config": api_dict, "secret_config": secret_dict }) else: msg = 'Project not Found' self.set_status(400) return self.write({ "status": "Bad Request", "message": msg, 'i18n': { "message": self.T(msg) } }) else: if "projects_folder" in self.interfaceConfig: self._projects_path = self.interfaceConfig["projects_folder"] self.Projects = ProjectsList(self._projects_path) msg = "Application list" enviroment['projects_folder'] = self._projects_path running = ProjectRunner() self.set_status(200) return self.write({ "status": "OK", "message": msg, 'i18n': { "message": self.T(msg) }, "projects_list": [[ x[0], x[1], "running" if x[1] in running.projects else "stopped" ] for x in self.Projects.projects_list], "authorization": authorization, "enviroment": enviroment, }) else: msg = "Get project list" self.set_status(202) self.write({ "status": "Accepted", "message": msg, "authorization": authorization, "enviroment": enviroment, 'i18n': { "message": self.T(msg) } })
def __init__(self): self._projectdata_dir = os.path.join(appdirs.user_data_dir(), "phanterpwa") self._projectdata_dir_gui = os.path.join(self._projectdata_dir, "gui") if not os.path.isdir(self._projectdata_dir): os.makedirs(self._projectdata_dir, exist_ok=True) if not os.path.isdir(self._projectdata_dir_gui): os.makedirs(self._projectdata_dir_gui, exist_ok=True) self._projects_path = None self.ProjectsPWA = None self.ProjectPWA = None self.ConfigAPI = None self.ConfigAPP = None self.CONFIG = config(self._projectdata_dir_gui) app_folder_data = "" if "projects_folder" in self.CONFIG: if os.path.isdir(self.CONFIG["projects_folder"]): self.projects_folder = self.CONFIG["projects_folder"] app_folder_data = self.projects_folder else: self.projects_folder = os.getcwd() self.start() self.tkInstance.withdraw() self.maxheight = 400 self.ApplicationsTornado = {} scrollbar = Scrollbar(self.tkInstance, orient=VERTICAL) scrollbar.pack(side=RIGHT, fill=Y, expand=FALSE) self.frame_canvas = tk.Canvas( self.tkInstance, bd=0, highlightthickness=0, yscrollcommand=scrollbar.set ) self.frame_canvas.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.frame_canvas.yview) self.frame_canvas.pack(side=LEFT, fill=Y, expand=TRUE) self.tkInstance.title(T("Project Folder - PhanterPWA")) self.tkInstance.iconbitmap(os.path.join(CURRENT_DIR, "grafics", "icon.ico")) frame = tk.Frame(self.frame_canvas) row = 0 aLabel = ttk.Label(frame, text=T("Where will your projects be saved?"), font='default 14 bold') aLabel.grid(column=0, row=row, columnspan=3, padx=(10, 0), pady=(20, 5)) row += 1 app_folder_label = ttk.Label(frame, text=T("Path")) app_folder_label.grid(column=0, row=row, padx=(20, 0), pady=(5, 20)) self.app_folder_input = ttk.Entry(frame, width=60) self.app_folder_input.insert(0, app_folder_data) self.app_folder_input.grid(column=1, row=row, padx=(0, 0), pady=(5, 20)) button = ttk.Button(frame, text=T("Change"), command=lambda: self.setEntryFolder(self.app_folder_input)) button.grid(column=2, row=row, padx=(0, 20), pady=(5, 20), sticky="w") row += 1 self.buttonOK = ttk.Button(frame, text=T("OK"), command=self.open_window_projects, state=DISABLED) self.buttonOK.grid(column=0, row=row, columnspan=3, padx=10, pady=(5, 30)) self.frame_canvas.create_window((0, 0), window=frame, anchor='nw') self.frame_canvas.bind('<Configure>', self.onConfigure) self.tkInstance.resizable(0, 0) self.tkInstance.maxsize(width=0, height=self.maxheight) self.tkInstance.resizable(0, 0) self.tkInstance.deiconify() self.tkInstance.protocol("WM_DELETE_WINDOW", self.onClosing) self.tkInstance.attributes('-topmost', True) self.tkInstance.update() self.tkInstance.attributes('-topmost', False) self.tkInstance.mainloop()
from phanterpwa.tools import ( config ) from phanterpwa.compiler import Compiler #from phanterpwa.interface.graphic import start try: import tkinter as Tk from phanterpwa.interface.admin_tk import start except: def start(): print("The tkinter fails. Your Python may not be configured for Tk") from phanterpwa.interface.cli import Cli CURRENT_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__))) CWD = os.path.join(CURRENT_DIR, "interface") CONFIG = config(CWD) ENV_PYTHON = os.path.normpath(sys.executable) parser = argparse.ArgumentParser(description="".join(['Without arguments the phanterpwa GUI will be executed,\n', ' if there is an error try to use the CLI version.'])) def start_server(projectPath): target = os.path.normpath(os.path.join(CURRENT_DIR, "server.py")) command = " ".join([ENV_PYTHON, target]) subprocess.run(command, cwd=projectPath, shell=True) def CLEAR_CONSOLE(): os.system('cls' if os.name == 'nt' else 'clear')