import os from datetime import datetime from flask import Flask import mysql.connector class DBManager: def __init__(self, database='flask', host="db", user="flasku", password="flaskp"): envuser = os.getenv("MYSQL_USER") envpass = os.getenv("MYSQL_PASSWORD") #printf("DEBUG:" + envuser + envpass) self.connection = mysql.connector.connect( user=envuser, #user=user, password=envpass, #password=password, host=host, # name of the mysql service as set in the docker compose file database=database #auth_plugin='mysql_native_password' ) 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, 'Database entry #%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 server = Flask(__name__) conn = None @server.route('/') def listBlog(): global conn if not conn: conn = DBManager() conn.populate_db() rec = conn.query_titles() response = '' for c in rec: response = response + '
Log: ' + c + '
' dt = datetime.now() dtFormatted = dt.strftime("%Y-%m-%d %H:%M") response = response + '
Delta: ' + dtFormatted + '
' return response if __name__ == '__main__': server.run()