Remove SQLAlchemy code.

This commit is contained in:
yohan 2024-06-06 14:01:31 +02:00
parent f889641d59
commit df87a1deb8
5 changed files with 7 additions and 81 deletions

View File

@ -7,7 +7,6 @@ ENV PIP_BREAK_SYSTEM_PACKAGES 1
RUN pip install flask-restx==1.3.0 RUN pip install flask-restx==1.3.0
WORKDIR /root WORKDIR /root
COPY thermostat.py /root/ COPY thermostat.py /root/
#COPY migrate_db.sh /root/
COPY entrypoint.sh /root/ COPY entrypoint.sh /root/
ENV FLASK_APP thermostat.py ENV FLASK_APP thermostat.py
ENTRYPOINT ["/root/entrypoint.sh"] ENTRYPOINT ["/root/entrypoint.sh"]

View File

@ -1,6 +1,3 @@
flask_settings:
SQLALCHEMY_DATABASE_URI: 'sqlite:///thermostat.db'
api_key: "FIXME" api_key: "FIXME"
flask_settings_dev: flask_settings_dev:

View File

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

View File

@ -1,3 +0,0 @@
#!/bin/bash
flask db init; flask db migrate -m "Database migration." && flask db upgrade

View File

@ -16,24 +16,12 @@ from threading import Thread
from threading import Lock from threading import Lock
import sqlite3 import sqlite3
#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
# python3-flask 2.2.2-3 all micro web framework based on Werkzeug and Jinja2 - Python 3.x # python3-flask 2.2.2-3 all micro web framework based on Werkzeug and Jinja2 - Python 3.x
# python3-flask-migrate 4.0.4-1 all SQLAlchemy migrations for Flask using Alembic and Python 3
# python3-flask-sqlalchemy 3.0.3-1 all adds SQLAlchemy support to your Python 3 Flask application
# alembic 1.8.1-2 all lightweight database migration tool for SQLAlchemy
# python3-alembic 1.8.1-2 all lightweight database migration tool for SQLAlchemy - Python module
# python3-sqlalchemy 1.4.46+ds1-1 all SQL toolkit and Object Relational Mapper for Python 3
# python3-sqlalchemy-ext:i386 1.4.46+ds1-1+b1 i386 SQL toolkit and Object Relational Mapper for Python3 - C extension
# flask-restx 1.3.0 # flask-restx 1.3.0
# Flask-SQLAlchemy documentation: https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/quickstart/ # Flask-RESTX documentation: https://flask-restx.readthedocs.io/en/latest/
# We use SQLAlchemy ORM style 2.x: https://docs.sqlalchemy.org/en/20/tutorial/data_select.html
xprint_lock = Lock() xprint_lock = Lock()
logging.basicConfig(level=logging.WARNING) logging.basicConfig(level=logging.WARNING)
@ -154,8 +142,6 @@ def get_metric(metric, current_time, interval):
return None return None
def get_forced_mode(cursor): def get_forced_mode(cursor):
#with app.app_context():
# row = db.session.execute(db.select(Set_mode.value, Set_mode.timestamp)).first()
cursor.execute("SELECT value, timestamp FROM set_mode WHERE name='mode'") cursor.execute("SELECT value, timestamp FROM set_mode WHERE name='mode'")
row = cursor.fetchone() row = cursor.fetchone()
if row is None: if row is None:
@ -174,8 +160,7 @@ def get_forced_mode(cursor):
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) api = Api(app, version='1.0', title='Thermostat and load shedder',
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')
@ -188,20 +173,6 @@ cursor.execute("CREATE TABLE IF NOT EXISTS set_mode (name TEXT PRIMARY KEY DEFAU
value TEXT NOT NULL, \ value TEXT NOT NULL, \
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL)") timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL)")
# 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 = {
# 'value': fields.String(required=True, description='value', enum=targets+modes),
#}
#Set_mode_model = api.model('Set_mode_Model', Set_mode_resource_fields)
Set_mode_parser = api.parser() Set_mode_parser = api.parser()
Set_mode_parser.add_argument( Set_mode_parser.add_argument(
"value", type=str, choices=targets+modes, required=True, help="value", location="json" "value", type=str, choices=targets+modes, required=True, help="value", location="json"
@ -235,16 +206,15 @@ class Status_thermostat(Resource):
logging.debug(result) logging.debug(result)
return result return result
Set_verbosity_resource_fields = { Set_verbosity_parser = api.parser()
'value': fields.String(required=True, description='Verbosity', enum=["DEBUG", "INFO", "WARNING"]) Set_verbosity_parser.add_argument(
} "value", type=str, choices=["DEBUG", "INFO", "WARNING"], required=True, help="Verbosity", location="json"
)
Set_verbosity_model = api.model('Set_verbosity_Model', Set_verbosity_resource_fields)
@ns_thermostat.route('/set_verbosity') @ns_thermostat.route('/set_verbosity')
class Set_verbosity_thermostat(Resource): class Set_verbosity_thermostat(Resource):
@auth_required @auth_required
@api.expect(Set_verbosity_model, validate=True) @api.expect(Set_verbosity_parser, validate=True)
def put(self): def put(self):
if api.payload["value"] == 'DEBUG': if api.payload["value"] == 'DEBUG':
logging.getLogger().setLevel(logging.DEBUG) logging.getLogger().setLevel(logging.DEBUG)
@ -255,9 +225,6 @@ 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():
# db.create_all()
#migrate = Migrate(app, db, compare_type=True)
# TODO: Get Linky overload warning # TODO: Get Linky overload warning
@ -292,25 +259,6 @@ def thermostat_loop():
# break # break
if new_forced_mode is not None: if new_forced_mode is not None:
#with app.app_context():
# data = Set_mode(value=new_forced_mode)
# logging.debug("Update mode in DB")
# try:
# cur_mode = db.session.execute(db.select(Set_mode).filter_by(name="mode")).scalar_one()
# logging.debug("Remove current mode: "+str(cur_mode.value))
# db.session.delete(cur_mode)
# except Exception as e:
# db.session.rollback()
# logging.debug(e)
# try:
# logging.debug("Insert mode in DB")
# db.session.add(data)
# db.session.commit()
# except Exception as e:
# db.session.rollback()
# db.session.commit()
# 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)
@ -411,7 +359,6 @@ t1.daemon = True
t1.start() t1.start()
logging.info("====== Ended successfully ======") logging.info("====== Ended successfully ======")
#import argparse
#import signal #import signal
#from threading import Event #from threading import Event
#from http.server import BaseHTTPRequestHandler #from http.server import BaseHTTPRequestHandler
@ -419,19 +366,6 @@ logging.info("====== Ended successfully ======")
#import socketserver #import socketserver
#p = argparse.ArgumentParser(description='Thermostat and load shedder.')
#p.add_argument("-v", "--verbosity", help="Increase output verbosity",
# type=str, choices=['DEBUG', 'INFO', 'WARNING'], default='INFO')
#args = p.parse_args()
#
#verbosity = args.verbosity
#if verbosity == 'DEBUG':
# logging.basicConfig(level=logging.DEBUG)
#elif verbosity == 'INFO':
# logging.basicConfig(level=logging.INFO)
#elif verbosity == 'WARNING':
# logging.basicConfig(level=logging.WARNING)
#
# #
#def api_help(): #def api_help():
# return """ # return """