Move config to database

This commit is contained in:
Phillip Kühne 2023-03-30 02:22:46 +02:00
parent d33006251e
commit 98981b1e1e
Signed by: phillip
GPG Key ID: E4C1C4D2F90902AA
3 changed files with 83 additions and 30 deletions

View File

@ -42,7 +42,7 @@ def enqueue():
database.add_entry(name, song_id, client_id) database.add_entry(name, song_id, client_id)
return Response('{"status":"OK"}', mimetype='text/json') return Response('{"status":"OK"}', mimetype='text/json')
else: else:
if accept_entries: if helpers.get_accept_entries(app):
if not request.json: if not request.json:
print(request.data) print(request.data)
abort(400) abort(400)
@ -91,6 +91,8 @@ def settings_post():
else: else:
abort(400) abort(400)
helpers.persist_config(app=app)
return render_template('settings.html', app=app, auth=basic_auth.authenticate()) return render_template('settings.html', app=app, auth=basic_auth.authenticate())
@ -187,9 +189,8 @@ def mark_transferred(entry_id):
@nocache @nocache
@basic_auth.required @basic_auth.required
def set_accept_entries(value): def set_accept_entries(value):
global accept_entries
if (value == '0' or value == '1'): if (value == '0' or value == '1'):
accept_entries = bool(int(value)) helpers.set_accept_entries(app,bool(int(value)))
return Response('{"status": "OK"}', mimetype='text/json') return Response('{"status": "OK"}', mimetype='text/json')
else: else:
return Response('{"status": "FAIL"}', mimetype='text/json', status=400) return Response('{"status": "FAIL"}', mimetype='text/json', status=400)
@ -198,7 +199,7 @@ def set_accept_entries(value):
@app.route("/api/entries/accept") @app.route("/api/entries/accept")
@nocache @nocache
def get_accept_entries(): def get_accept_entries():
global accept_entries accept_entries = helpers.get_accept_entries(app)
return Response('{"status": "OK", "value": '+str(int(accept_entries))+'}', mimetype='text/json') return Response('{"status": "OK", "value": '+str(int(accept_entries))+'}', mimetype='text/json')
@ -238,6 +239,7 @@ def activate_job():
database.create_done_song_table() database.create_done_song_table()
database.create_list_view() database.create_list_view()
database.create_done_song_view() database.create_done_song_view()
database.create_config_table()
helpers.setup_config(app) helpers.setup_config(app)

View File

@ -78,6 +78,14 @@ def create_done_song_view():
WHERE done_songs.Song_Id=songs.Id""") WHERE done_songs.Song_Id=songs.Id""")
def create_config_table():
with get_db_engine().connect() as conn:
conn.execute("""CREATE TABLE IF NOT EXISTS `config` (
`Key` VARCHAR(50) NOT NULL PRIMARY KEY,
`Value` TEXT
)""")
def get_list(): def get_list():
with get_db_engine().connect() as conn: with get_db_engine().connect() as conn:
cur = conn.execute("SELECT * FROM Liste") cur = conn.execute("SELECT * FROM Liste")
@ -177,7 +185,25 @@ def delete_entries(ids):
return -1 return -1
def delete_all_entries(): def delete_all_entries() -> bool:
with get_db_engine().connect() as conn: with get_db_engine().connect() as conn:
conn.execute("DELETE FROM entries") conn.execute("DELETE FROM entries")
return True return True
def get_config(key: str) -> str:
with get_db_engine().connect() as conn:
cur = conn.execute("SELECT `Value` FROM config WHERE `Key`=%s", (key,))
return cur.fetchall()[0][0]
def set_config(key: str, value: str) -> bool:
with get_db_engine().connect() as conn:
conn.execute("INSERT INTO config (`Key`, `Value`) VALUES (%s,%s) ON DUPLICATE KEY UPDATE `Value`=%s", (key, value, value))
return True
def get_config_list() -> dict:
with get_db_engine().connect() as conn:
cur = conn.execute("SELECT * FROM config")
result_dict = {}
for row in cur.fetchall():
result_dict[row[0]] = row[1]
return result_dict

View File

@ -3,9 +3,10 @@ from bs4 import BeautifulSoup
import json import json
import os import os
import uuid import uuid
from flask import make_response from flask import make_response, Flask
from functools import wraps, update_wrapper from functools import wraps, update_wrapper
from datetime import datetime from datetime import datetime
import database
data_directory = "data" data_directory = "data"
config_file = data_directory+"/config.json" config_file = data_directory+"/config.json"
@ -33,9 +34,17 @@ def is_valid_uuid(val):
return False return False
def check_config_exists(): def check_config_exists():
return os.path.isfile(config_file) eng = database.get_db_engine()
with eng.connect() as conn:
if conn.dialect.has_table(conn, 'config'):
if (conn.execute("SELECT COUNT(*) FROM config").fetchone()[0] > 0): # type: ignore
return True
else:
return False
else:
return False
def load_version(app): def load_version(app: Flask):
if os.environ.get("SOURCE_VERSION"): if os.environ.get("SOURCE_VERSION"):
app.config['VERSION'] = os.environ.get("SOURCE_VERSION")[0:7] # type: ignore app.config['VERSION'] = os.environ.get("SOURCE_VERSION")[0:7] # type: ignore
elif os.path.isfile(".version"): elif os.path.isfile(".version"):
@ -48,7 +57,7 @@ def load_version(app):
else: else:
app.config['VERSION'] = "" app.config['VERSION'] = ""
def load_dbconfig(app): def load_dbconfig(app: Flask):
if os.environ.get("FLASK_ENV") == "development": if os.environ.get("FLASK_ENV") == "development":
app.config['DBCONNSTRING'] = os.environ.get("DBSTRING") app.config['DBCONNSTRING'] = os.environ.get("DBSTRING")
else: else:
@ -70,29 +79,45 @@ def load_dbconfig(app):
else: else:
app.config['DBCONNSTRING'] = "" app.config['DBCONNSTRING'] = ""
else: else:
app.config['DBCONNSTRING'] = "" exit("No database connection string found. Cannot continue. Please set the environment variable DBSTRING or create a file .dbconn in the root directory of the project.")
def setup_config(app): # Check if config exists in DB, if not, create it.
if os.environ.get("DEPLOYMENT_PLATFORM") == "Docker": def setup_config(app: Flask):
app.config['BASIC_AUTH_USERNAME'] = os.environ.get('BASIC_AUTH_USERNAME') if check_config_exists():
app.config['BASIC_AUTH_PASSWORD'] = os.environ.get('BASIC_AUTH_PASSWORD') config = database.get_config_list()
app.config['ENTRY_QUOTA'] = os.environ.get('ENTRY_QUOTA') print("Loaded existing config")
app.config['MAX_QUEUE'] = os.environ.get('MAX_QUEUE')
else: else:
if check_config_exists(): config = {'username': 'admin', 'password': 'changeme', 'entryquota': 3, 'maxqueue': 20, 'entries_allowed': 1}
config = json.load(open(config_file)) for key, value in config.items():
with open(config_file, 'r') as handle: database.set_config(key, value)
config = json.load(handle) print("Created new config")
print("Loaded existing config") app.config['BASIC_AUTH_USERNAME'] = config['username']
else: app.config['BASIC_AUTH_PASSWORD'] = config['password']
config = {'username': 'admin', 'password': 'changeme', 'entryquota': 3, 'maxqueue': 20} app.config['ENTRY_QUOTA'] = config['entryquota']
with open(config_file, 'w') as handle: app.config['MAX_QUEUE'] = config['maxqueue']
json.dump(config, handle, indent=4, sort_keys=True) app.config['ENTRIES_ALLOWED'] = bool(config['entries_allowed'])
print("Wrote new config")
app.config['BASIC_AUTH_USERNAME'] = config['username'] # set queue admittance
app.config['BASIC_AUTH_PASSWORD'] = config['password'] def set_accept_entries(app: Flask, allowed: bool):
app.config['ENTRY_QUOTA'] = config['entryquota'] if allowed:
app.config['MAX_QUEUE'] = config['maxqueue'] app.config['ENTRIES_ALLOWED'] = True
database.set_config('entries_allowed', '1')
else:
app.config['ENTRIES_ALLOWED'] = False
database.set_config('entries_allowed', '0')
# get queue admittance
def get_accept_entries(app: Flask) -> bool:
state = bool(int(database.get_config('entries_allowed')))
app.config['ENTRIES_ALLOWED'] = state
return state
# Write settings from current app.config to DB
def persist_config(app: Flask):
config = {'username': app.config['BASIC_AUTH_USERNAME'], 'password': app.config['BASIC_AUTH_PASSWORD'], 'entryquota': app.config['ENTRY_QUOTA'], 'maxqueue': app.config['MAX_QUEUE']}
for key, value in config.items():
database.set_config(key, value)