def plug_in(appconfig, config=None): # plugin app global CONFIG if CONFIG is None: if config is not None: CONFIG = config.getsubdict(preamble=["plug_in_django_server"]) else: CONFIG = JsonDict( os.path.join( os.path.join(os.path.expanduser("~"), ".plug_in_django_server"), "plug_in_django_server_config.json", )) if config is not None: appconfig.config = config.getsubdict(preamble=[appconfig.name]) else: if appconfig.config is None: appconfig.config = CONFIG.getsubdict(preamble=[appconfig.name]) logger.info("plug in {} with the config-path:'{}'".format( appconfig.name, appconfig.config.file)) if not hasattr(appconfig, "baseurl"): setattr(appconfig, "baseurl", getattr(appconfig, "name")) apps = CONFIG.get("django_settings", "apps", "additional", default={}) if getattr(appconfig, "data_dir", False) is True: appconfig.data_dir = os.path.join(os.path.dirname(CONFIG.file), "{}_data".format(appconfig.name)) appconfig.data_dir_url = ("/" + appconfig.baseurl + ("/" if len(appconfig.baseurl) > 0 else "") + "{}_data".format(appconfig.name)) else: appconfig.data_dir = False apps[appconfig.name] = { "name": appconfig.name, "baseurl": getattr(appconfig, "baseurl"), "data_dir": appconfig.data_dir, } if appconfig.data_dir is not False: os.makedirs(appconfig.data_dir, exist_ok=True) CONFIG.put("django_settings", "apps", "additional", value=apps) CONFIG.save()
def main(): # main data dir os.makedirs(BASE_DIR, exist_ok=True) config = JsonDict(os.path.join(BASE_DIR, SNAKE_NAME + "_config.json")) # create basic logger logging_fmt = "%(asctime)s %(filename)s %(lineno)d %(name)s %(levelname)-8s %(message)s" logging.basicConfig( level=config.get("basic", "logging", "level", default=logging.DEBUG), format=logging_fmt, datefmt="(%H:%M:%S)", ) rotating_handler = RotatingFileHandler(os.path.join(BASE_DIR, 'log.log'), maxBytes=config.get("basic", "logging", "max_bytes", default=2**19), backupCount=config.get( "basic", "logging", "backup_count", default=10)) rotating_handler.setFormatter(logging.Formatter(logging_fmt)) logging.getLogger('').addHandler(rotating_handler) # logger.addHandler(logging.StreamHandler()) logger = logging.getLogger(BASENAME) coloredlogs.install(level='DEBUG', fmt=logging_fmt) logger.info("Use basedir: " + os.path.abspath(BASE_DIR)) # set server logger. from multi_purpose_arduino_controller.controll_server import manage as controll_server_manage # controll_server_manage.logger = logger # set_server_config controll_server_manage.CONFIG = config.getsubdict( preamble=['controll_server']) controll_server_manage.CONFIG.put("public", "site", "title", value=BASENAME) if config.get("basic", "mode", default=DEFAULT_MODE) == DEVELOPMENT_MODE: controll_server_manage.CONFIG.put("django_settings", "debug", value=True) else: controll_server_manage.CONFIG.put("django_settings", "debug", value=False) apps = [ "custom_accounts_django", "multi_purpose_arduino_controller.controll_server.board_controller", "django_websocket_server", "column_switcher.django_app" ] # apps.append("serverapps.board_creator") controll_server_manage.CONFIG.put("django_settings", "apps", "additional", value=apps) # create pending migrations if in development mode if config.get("basic", "mode", default=DEFAULT_MODE) == DEVELOPMENT_MODE: controll_server_manage.run(sys.argv[0], "makemigrations") controll_server_manage.run(sys.argv[0], "migrate") from django.contrib.auth.models import User superusers = User.objects.filter(is_superuser=True) if len(superusers) == 0: print("No Superuser specified") unsername = input("Enter Username: "******"Mail: ") pass1 = input("Password: "******"django_settings", "static_files", "dirs", value=[ os.path.abspath( os.path.join(os.path.dirname(__file__), "apis", "static")), # socketserver_instance.get_www_data_path(), # socketserver.TEMPDIR ], ) python_communicator = PythonCommunicator() # websocket server socketserver_instance = websocket_server.connect_to_first_free_port( data_dir=BASE_DIR, logger=logging.getLogger("websocket_server"), start_in_background=True, startport=config.get("websocket", "startport", default=9001), disable_encryption=config.get("websocket", "security", "disable_encryption", default=False)) # parse for boards parse_path_for_boards(os.path.join(os.path.dirname(__file__), "boards")) board_controller_api = BoardControllerAPI( python_communicator=python_communicator, websocket_server=socketserver_instance, data_dir=os.path.join(BASE_DIR, "BoardControllerAPI")) column_switcher_api = ColumnSwitcherAPI( python_communicator=python_communicator, websocket_server=socketserver_instance, data_dir=os.path.join(BASE_DIR, "ColumnSwitcherAPI")) # SerialReader sr = serialreader.SerialReader(communicator=python_communicator, start_in_background=True, config=config.getsubdict(["portdata"])) # starts django controll_server_manage.run( sys.argv[0], "runserver", "--noreload", "0.0.0.0:" + str( config.get( "controll_server", "django_settings", "port", default=8000)))
class DictTest(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp() self.temp_file = os.path.join(self.temp_dir, "d") with open(self.temp_file, "wb+") as f: f.write(b'{"test":"file"}') with open(self.temp_file, "r") as f: print(f.read(), self.temp_file) self.d = JsonDict(self.temp_file, backup=False) def tearDown(self): os.remove(self.temp_file) os.rmdir(self.temp_dir) def test_create_dict(self): assert list(self.d.data.keys()) == ["test"] assert self.d.get("test") == "file" def test_result_is_dict_to_json_dict(self): self.d.put("test", value={}) assert isinstance(self.d.get("test"), JsonSubDict) def test_create_subdict(self): print("A") print(self.d._file_size) sub1 = self.d.getsubdict("testsub", "dict") print("B") sub2 = self.d.getsubdict(["testsub", "dict"]) assert len(self.d.data.keys()) == 2 assert len(self.d["testsub"].keys()) == 1 def test_data_is_dict(self): sd = self.d.getsubdict("testsub", "dict") assert isinstance(self.d.data, dict) assert isinstance(sd.data, dict), (type(sd.data), sd.data) def test_double_open_file(self): d2 = JsonDict(self.d.file, backup=False) d2.put("second_entry", value=1) assert len(d2.data.keys()) == len(self.d.data.keys()) def test_list(self): self.d.put("list", value=[0, 1, 2]) l: json_dict.JsonList = self.d.get("list") l[1] = 10 l.reverse() assert all([l[i] == k for i, k in enumerate([2, 10, 0])]), str(l) assert l.pop(-1) == 0 assert all([l[i] == k for i, k in enumerate([2, 10])]), str(l) def test_time(self): t = time.time() json_dict.VERBOSE = False d = 1000 for i in range(d): self.d.put("second_entry", value=self.d.get("second_entry", default=0) + 1) print(time.time() - t) assert self.d.get("second_entry", default=1) == d json_dict.VERBOSE = True def test_empty_key(self): dic = { "data": { "": { "inempty": ["test"], } } } self.d.data = dic ds = JsonDict(self.d.file) print(ds)