added endpoint to upsert autos

This commit is contained in:
Ari Sosnovsky committed 2021-11-11 13:18:58 -05:00
1 parent 9e23885b28
commit 9ec15d5ab9
2 files changed
+25 -4

No files matched your search

+15 -2
View File
@@ -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,
)
+10 -2
View File
@@ -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()