From 9ccf112dafba97cef569f2a06ff03afc46a9b1af Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Thu, 1 Feb 2024 18:42:16 +0100 Subject: [PATCH] database init if it doesnt exist on background job start --- src/app.py | 15 ++++++++------- src/background.py | 6 ++++++ src/db.py | 22 ++++++++++++++++++++++ 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/app.py b/src/app.py index 851bd4b..c4a588e 100644 --- a/src/app.py +++ b/src/app.py @@ -7,13 +7,14 @@ from aliexpress import * app = Flask(__name__) CORS(app) -@app.route('/init') +@app.route('/init', methods = ['GET']) def init_db(): - print("init") - initialize() - return 'Hello, World!' + status = check_schema() + if not status: + initialize() + return str(status) -@app.route('/update') +@app.route('/update', methods = ['GET']) def update_hist(): print("update") update_items() @@ -44,13 +45,13 @@ def add_item(): # item not valid or can't be parsed return jsonify({'status': 1}), 400 -@app.route('/datahistory',methods = ['POST', 'GET']) +@app.route('/datahistory',methods = ['GET']) def data_history_request(): if request.method == 'GET': print("fetching data history") return jsonify(get_history()) -@app.route('/dataitem',methods = ['POST', 'GET']) +@app.route('/dataitem',methods = ['GET']) def data_item_request(): if request.method == 'GET': print("fetching data item") diff --git a/src/background.py b/src/background.py index 2fe06f3..1a18b9b 100644 --- a/src/background.py +++ b/src/background.py @@ -1,12 +1,18 @@ #!/usr/bin/python import requests, re, time, os +def init(): + url = "http://127.0.0.1:8080/init" + response = requests.get(url) + print(response) + def update(): url = "http://127.0.0.1:8080/update" response = requests.get(url) print(response) if __name__ == '__main__': + init() regex_time = re.compile(r'([1-9][0-9]*)([smhd])') formatted_time = os.environ.get('WAIT_TIME') units = { diff --git a/src/db.py b/src/db.py index e26f80e..bd45a81 100644 --- a/src/db.py +++ b/src/db.py @@ -193,3 +193,25 @@ def initialize(): connection.commit() connection.close() print("Database initialized") + +def check_schema(): + connection = connect_db() + cursor = connection.cursor() + cursor.execute(""" + select + exists( + select * + from pg_tables + where tablename = 'item' + ) + and exists( + select * + from pg_tables + where tablename = 'history' + ); + """) + result = cursor.fetchall() + cursor.close() + connection.close() + + return result[0][0]