From 6c8754131d4c3e0e8b4d6be6c632359edac2e9df Mon Sep 17 00:00:00 2001 From: Anca Date: Fri, 20 Mar 2020 01:49:52 +0100 Subject: [PATCH] Improved flask backend --- nginx-flask-mysql/backend/hello.py | 67 +++++++++++++++++------------- 1 file changed, 38 insertions(+), 29 deletions(-) diff --git a/nginx-flask-mysql/backend/hello.py b/nginx-flask-mysql/backend/hello.py index 35b6a33..40c3626 100755 --- a/nginx-flask-mysql/backend/hello.py +++ b/nginx-flask-mysql/backend/hello.py @@ -1,42 +1,51 @@ import os -import time from flask import Flask import mysql.connector -passfile = open('/run/secrets/db-password', 'r') -#give db some time to start -time.sleep(5) - -#connect to db -conn = mysql.connector.connect( - user='root', - password=passfile.read(), - host='db', # name of the mysql service as set in the docker-compose file - database='example', - auth_plugin='mysql_native_password' -) +class DBManager: + def __init__(self, database='example', host="db", user="root", password_file=None): + pf = open(password_file, 'r') + self.connection = mysql.connector.connect( + user=user, + password=pf.read(), + host=host, # name of the mysql service as set in the docker-compose file + database=database, + auth_plugin='mysql_native_password' + ) + pf.close() + self.cursor = self.connection.cursor() + + def populate_db(self): + self.cursor.execute('DROP TABLE IF EXISTS blog') + self.cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))') + self.cursor.executemany('INSERT INTO blog (id, title) VALUES (%s, %s);', [(i, 'Blog post #%d'% i) for i in range (1,5)]) + self.connection.commit() + + def query_titles(self): + self.cursor.execute('SELECT title FROM blog') + rec = [] + for c in self.cursor: + rec.append(c[0]) + return rec -passfile.close() -# populate db -cursor = conn.cursor() -def prepare_db(): - cursor.execute('DROP TABLE IF EXISTS blog') - cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))') - cursor.executemany('INSERT INTO blog (id, title) VALUES (%s, %s);', [(i, 'Blog post #%d'% i) for i in range (1,5)]) - conn.commit() -prepare_db() -# server -app = Flask(__name__) -@app.route('/') +server = Flask(__name__) +conn = None + +@server.route('/') def listBlog(): - cursor.execute('SELECT title FROM blog') + global conn + if not conn: + conn = DBManager(password_file='/run/secrets/db-password') + conn.populate_db() + rec = conn.query_titles() + response = '' - for c in cursor: - response = response + '
' + c[0] + '
' + for c in rec: + response = response + '
Hello ' + c + '
' return response if __name__ == '__main__': - app.run() + server.run()