diff --git a/api/src/api/routes/automations.py b/api/src/api/routes/automations.py index 7f7ef89..a6c956e 100644 --- a/api/src/api/routes/automations.py +++ b/api/src/api/routes/automations.py @@ -1,13 +1,15 @@ from typing import Optional from fastapi import APIRouter, HTTPException +from src.config.AutomationLoader import AutomationData, AutomationLoaderException + from ..config import automation_loader router = APIRouter() @router.get("/list") -def read_ping( +def list_autos( offset: int = 0, limit: int = 10, alias: Optional[str] = None, @@ -26,7 +28,7 @@ def read_ping( @router.get("/{index}") -def read_ping(index: int): +def get_auto(index: int): if auto := automation_loader.get(index): return auto else: @@ -38,3 +40,14 @@ def read_ping(index: int): "specified": index, }, ) + + +@router.post("/{index}") +def upsert_auto(index: int, auto: AutomationData): + try: + automation_loader.save(index, auto) + except AutomationLoaderException as err: + return HTTPException( + status_code=500, + detail=err.args, + ) diff --git a/api/src/db/connection.py b/api/src/db/connection.py index 75eaf32..2a01ad0 100644 --- a/api/src/db/connection.py +++ b/api/src/db/connection.py @@ -8,7 +8,7 @@ class HassDatabase: self.entities = None try: self.engine = create_engine(db_url) - self.connection = self.engine.connect() + self.connection = None except Exception as exc: if isinstance(exc, ImportError): raise RuntimeError( @@ -23,11 +23,19 @@ class HassDatabase: return self.url.scheme.split("+")[0] def execute_sql(self, sql: str, **args): + self.connect() resp = self.engine.execute(text(sql), **args) + self.close() return resp.fetchall() + def connect(self): + if self.connection is None: + self.connection = self.engine.connect() + def close(self): - self.connection.close() + if self.connection is not None: + self.connection.close() + self.connection = None def __del__(self): self.close()