2020-03-17 20:55:32 +00:00
|
|
|
import os
|
2020-03-05 16:28:07 +00:00
|
|
|
from flask import Flask
|
2020-03-17 20:55:32 +00:00
|
|
|
import mysql.connector
|
|
|
|
|
2020-03-20 00:49:52 +00:00
|
|
|
|
|
|
|
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(),
|
2022-05-10 09:59:25 +00:00
|
|
|
host=host, # name of the mysql service as set in the docker compose file
|
2020-03-20 00:49:52 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
server = Flask(__name__)
|
|
|
|
conn = None
|
|
|
|
|
|
|
|
@server.route('/')
|
2020-03-17 20:55:32 +00:00
|
|
|
def listBlog():
|
2020-03-20 00:49:52 +00:00
|
|
|
global conn
|
|
|
|
if not conn:
|
|
|
|
conn = DBManager(password_file='/run/secrets/db-password')
|
|
|
|
conn.populate_db()
|
|
|
|
rec = conn.query_titles()
|
|
|
|
|
2020-03-17 20:55:32 +00:00
|
|
|
response = ''
|
2020-03-20 00:49:52 +00:00
|
|
|
for c in rec:
|
|
|
|
response = response + '<div> Hello ' + c + '</div>'
|
2020-03-17 20:55:32 +00:00
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-03-20 00:49:52 +00:00
|
|
|
server.run()
|