コード例 #1
0
 async def handle_get(self, request):
     if not self.controller.running:
         await spawn(request, self.controller.usbrxhandler())
     if request.path == "/schema":
         resp = self.controller.schema.copy()
         resp["controller"] = self.controller.__class__.__name__
         return web.json_response(resp)
     path, getmodel = ("/",
                       True) if request.path == "/model" else (request.path,
                                                               False)
     if self.logger.isEnabledFor(logging.DEBUG):
         self.logger.debug(f"{path}")
     data = Utility.parse_path_against_schema_and_model(self.model,
                                                        self.schema,
                                                        path,
                                                        read_write="r")
     if data["error"] is not None:
         response = data["error"]
         self.logger.error(f"{response}")
     elif data.get("routine") is not None:
         res = await getattr(self.controller,
                             data["routine"])(*data["args"])
         response = res
     else:
         response = {
             "path": data["path_string"],
             "data": data["model_data"]
         }
     if getmodel:
         response["controller"] = self.controller.__class__.__name__
     return web.json_response(response)
コード例 #2
0
ファイル: test_usbRec.py プロジェクト: IanDLacy/pyGizmoServer
    def processandcheck(self, msg):
        d = self.controller.recUsb(msg)

        for pd in d:
            results = Utility.parse_path_against_schema_and_model(
                path=pd["path"],
                schema=self.schema,
                model=self.mockvars.mock_model)
            self.checkmatch(results["model_data"], pd["data"], pd["path"])
コード例 #3
0
 def test_parse_path_against_schema_and_model_bad_path_2(self):
     self.get_instance()
     self.path = "./.relayController.misspelled[10]/enabled"
     result = Utility.parse_path_against_schema_and_model(
         self.model, self.schema, self.path, read_write="w"
     )
     assert result["error"] == "PATH ERROR: /relayController/misspelled"
     assert result["path_up_to_array_index"] is None
     assert result["path_string"] is None
     assert result["model_data"] is None
     assert result["routine"] is None
     assert result["args"] is None
コード例 #4
0
 def test_parse_path_against_schema_and_model_indexed_write(self):
     self.get_instance()
     self.path = ".relayController/relays[3]/enabled"
     result = Utility.parse_path_against_schema_and_model(
         self.model, self.schema, self.path, read_write="w"
     )
     assert result["path_up_to_array_index"] == "/relayController/relays"
     assert result["path_string"] == "/relayController/relays/3/enabled"
     assert not result["model_data"]
     assert result["routine"] == "setRelay"
     assert result["args"] == [3]
     assert result["error"] is None
コード例 #5
0
 def test_parse_path_against_schema_and_model_read_root_directory(self):
     self.get_instance()
     self.path = "/"
     result = Utility.parse_path_against_schema_and_model(
         self.model, self.schema, self.path, read_write="r"
     )
     assert result["path_up_to_array_index"] == "/"
     assert result["path_string"] == "/"
     assert result["model_data"] == self.model
     assert result["routine"] is None
     assert result["args"] is None
     assert result["error"] is None
コード例 #6
0
 async def handle_patch_from_client(self, request):
     if not self.controller.running:
         await spawn(request, self.controller.usbrxhandler())
     request = json.loads(await request.text())
     if self.logger.isEnabledFor(logging.DEBUG):
         self.logger.debug(f"{request}")
     if not isinstance(request, list):
         request = [request]
     response = []
     for r in request:
         path = r.get("path")
         if path is None:
             raise ValueError(f"no path provided in request: {r}")
         data = Utility.parse_path_against_schema_and_model(self.model,
                                                            self.schema,
                                                            path,
                                                            read_write="w")
         if data["error"] is not None:
             self.logger.error(f"{data['error']}")
             return web.json_response([{"error": data["error"]}])
         value = r.get("value")
         if value is not None:
             data["args"].append(value)
         # call the specified function with the associated parameters
         try:
             getattr(self.controller, data["routine"])(*data["args"])
         except Exception as e:
             if self.logger.isEnabledFor(logging.DEBUG):
                 self.logger.debug(f"{e}")
             data["error"] = f"bad request: {r}\n{e}"
             return web.json_response([{"error": data["error"]}])
         r["path"] = data["path_string"]
         response.append({"path": data["path_string"], "data": value})
     self.controller.finished()
     """
     create and apply the requested PATCH to the model
     """
     patch = jsonpatch.JsonPatch(request)
     jsonpatch.apply_patch(self.model, patch, in_place=True)
     return web.json_response(response)
コード例 #7
0
)
filehandler = logging.FileHandler(filename=cfg.logging.file.filename, mode="w")
filehandler.setLevel(getattr(logging, cfg.logging.file.loglevel))
filehandler.setFormatter(formatter)
consolehandler = logging.StreamHandler(sys.stdout)
consolehandler.setLevel(getattr(logging, cfg.logging.console.loglevel))
consolehandler.setFormatter(formatter)
gizmo_logger.addHandler(filehandler)
gizmo_logger.addHandler(consolehandler)
gizmo_logger.propagate = False
""" setup controller """
controller = getattr(
    importlib.import_module(f"{cfg.controller}.{cfg.controller}"),
    cfg.controller)()
""" set initial model """
model = Utility.initialize_model_from_schema(controller.schema)
""" setup modification, query handlers """
modification_handler = ModificationHandler(controller, model=model)
query_handler = QueryHandler(cfg.ws.ip, cfg.ws.port, controller, model=model)
controller.setcallback(query_handler.handle_updates)


async def get_index(request):
    return web.FileResponse('./dist/index.html')


async def get_favicon(request):
    return web.FileResponse('./dist/favicon.ico')


def make_app():