Disable SQLAlchemy.

This commit is contained in:
yohan 2024-06-06 12:10:18 +02:00
parent 0117512928
commit 0a2e7a25b0
2 changed files with 52 additions and 41 deletions

View File

@ -1,3 +1,4 @@
#!/bin/bash #!/bin/bash
/root/migrate_db.sh && exec flask run #/root/migrate_db.sh && exec flask run
exec flask run

View File

@ -1,8 +1,6 @@
from flask import Flask, request from flask import Flask, request
from flask_restx import Api, Resource, fields from flask_restx import Api, Resource, fields
from functools import wraps from functools import wraps
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import json import json
import logging import logging
import yaml import yaml
@ -16,8 +14,11 @@ import requests
import subprocess import subprocess
from threading import Thread from threading import Thread
from threading import Lock from threading import Lock
import sqlalchemy.exc
from sqlalchemy.dialects.sqlite import insert as sqlite_upsert #import sqlalchemy.exc
#from sqlalchemy.dialects.sqlite import insert as sqlite_upsert
#from flask_sqlalchemy import SQLAlchemy
#from flask_migrate import Migrate
# This code has been written for # This code has been written for
# python3 3.11.2-1+b1 # python3 3.11.2-1+b1
@ -151,14 +152,13 @@ def get_metric(metric, current_time, interval):
sys.stdout.flush() sys.stdout.flush()
return None return None
def get_forced_mode(): def get_forced_mode(cursor):
with app.app_context(): #with app.app_context():
row = db.session.execute(db.select(Set_mode.value, Set_mode.timestamp)).first() # row = db.session.execute(db.select(Set_mode.value, Set_mode.timestamp)).first()
cursor.execute("SELECT value, timestamp FROM set_mode WHERE name='mode'")
row = cursor.fetchone()
if row is None: if row is None:
return None return None
#cur.execute("SELECT value, timestamp FROM set_mode WHERE name='mode'")
#row = cur.fetchone()
xprint(row)
data = dict(zip(['value', 'timestamp'], row)) data = dict(zip(['value', 'timestamp'], row))
timestamp = data['timestamp'].replace(tzinfo=timezone.utc).timestamp() timestamp = data['timestamp'].replace(tzinfo=timezone.utc).timestamp()
# We ignore old targets but never ignore absence modes # We ignore old targets but never ignore absence modes
@ -173,18 +173,27 @@ def get_forced_mode():
app = Flask(__name__) app = Flask(__name__)
app.config.from_mapping(flask_settings) app.config.from_mapping(flask_settings)
app.config.from_mapping(flask_settings_env) app.config.from_mapping(flask_settings_env)
db = SQLAlchemy(app) #db = SQLAlchemy(app)
api = Api(app, version='1.0', title='Thermostat', api = Api(app, version='1.0', title='Thermostat',
description='API to read and set thermostat.', authorizations=authorizations) description='API to read and set thermostat.', authorizations=authorizations)
ns_thermostat = api.namespace('thermostat/', description='Thermostat API') ns_thermostat = api.namespace('thermostat/', description='Thermostat API')
# if the database file does not exist it will be created automatically
dbconn = sqlite3.connect("./instance/thermostat.db")
cursor = dbconn.cursor()
# we will only use name="mode" for set_mode table # we will only use name="mode" for set_mode table
# only modes that are set manually will be recorded in the database # only modes that are set manually will be recorded in the database
class Set_mode(db.Model): cursor.execute("CREATE TABLE IF NOT EXISTS set_mode (name TEXT PRIMARY KEY DEFAULT 'mode' NOT NULL, \
__tablename__ = "set_mode" value TEXT NOT NULL, \
name = db.Column(db.String, primary_key=True, default='mode', server_default='mode', nullable=False) timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL)")
value = db.Column(db.String, nullable=False)
timestamp = db.Column(db.DateTime, server_default=db.text("CURRENT_TIMESTAMP"), nullable=False) # we will only use name="mode" for set_mode table
# only modes that are set manually will be recorded in the database
#class Set_mode(db.Model):
# __tablename__ = "set_mode"
# name = db.Column(db.String, primary_key=True, default='mode', server_default='mode', nullable=False)
# value = db.Column(db.String, nullable=False)
# timestamp = db.Column(db.DateTime, server_default=db.text("CURRENT_TIMESTAMP"), nullable=False)
Set_mode_resource_fields = { Set_mode_resource_fields = {
'name': fields.String(description='mode type'), 'name': fields.String(description='mode type'),
@ -237,9 +246,9 @@ class Set_verbosity_thermostat(Resource):
return "OK", 201 return "OK", 201
api.add_namespace(ns_thermostat) api.add_namespace(ns_thermostat)
with app.app_context(): #with app.app_context():
db.create_all() # db.create_all()
migrate = Migrate(app, db, compare_type=True) #migrate = Migrate(app, db, compare_type=True)
# TODO: Get Linky overload warning # TODO: Get Linky overload warning
@ -262,6 +271,7 @@ def thermostat_loop():
global forced_mode global forced_mode
global new_forced_mode global new_forced_mode
global current_time global current_time
global cursor
while True: while True:
# if stop.is_set(): # if stop.is_set():
@ -271,27 +281,27 @@ def thermostat_loop():
# break # break
if new_forced_mode is not None: if new_forced_mode is not None:
with app.app_context(): #with app.app_context():
data = Set_mode(value=new_forced_mode) # data = Set_mode(value=new_forced_mode)
logging.debug("Update mode in DB") # logging.debug("Update mode in DB")
try: # try:
cur_mode = db.session.execute(db.select(Set_mode).filter_by(name="mode")).scalar_one() # cur_mode = db.session.execute(db.select(Set_mode).filter_by(name="mode")).scalar_one()
logging.debug("Remove current mode: "+str(cur_mode.value)) # logging.debug("Remove current mode: "+str(cur_mode.value))
db.session.delete(cur_mode) # db.session.delete(cur_mode)
except Exception as e: # except Exception as e:
db.session.rollback() # db.session.rollback()
logging.debug(e) # logging.debug(e)
try: # try:
logging.debug("Insert mode in DB") # logging.debug("Insert mode in DB")
db.session.add(data) # db.session.add(data)
db.session.commit() # db.session.commit()
except Exception as e: # except Exception as e:
db.session.rollback() # db.session.rollback()
db.session.commit() # db.session.commit()
logging.error(e) # logging.error(e)
#cursor.execute("INSERT OR REPLACE INTO set_mode (value) VALUES ('"+new_forced_mode+"')") cursor.execute("INSERT OR REPLACE INTO set_mode (value) VALUES ('"+new_forced_mode+"')")
#dbconn.commit() dbconn.commit()
logging.info("Switch to "+new_forced_mode) logging.info("Switch to "+new_forced_mode)
target_name = new_forced_mode target_name = new_forced_mode
new_forced_mode = None new_forced_mode = None
@ -301,7 +311,7 @@ def thermostat_loop():
current_date = datetime.now() current_date = datetime.now()
today_awake_time = current_date.replace(hour=int(awake_hour.split(':')[0]), minute=int(awake_hour.split(':')[1]), second=0, microsecond=0) today_awake_time = current_date.replace(hour=int(awake_hour.split(':')[0]), minute=int(awake_hour.split(':')[1]), second=0, microsecond=0)
today_sleep_time = current_date.replace(hour=int(sleep_hour.split(':')[0]), minute=int(sleep_hour.split(':')[1]), second=0, microsecond=0) today_sleep_time = current_date.replace(hour=int(sleep_hour.split(':')[0]), minute=int(sleep_hour.split(':')[1]), second=0, microsecond=0)
forced_mode = get_forced_mode() forced_mode = get_forced_mode(cursor)
if forced_mode is not None and forced_mode in targets: if forced_mode is not None and forced_mode in targets:
if target_name != forced_mode: if target_name != forced_mode:
target_name = forced_mode target_name = forced_mode