Improved flask backend

master
Anca 5 years ago
parent dcac9e0722
commit 6c8754131d

@ -1,42 +1,51 @@
import os import os
import time
from flask import Flask from flask import Flask
import mysql.connector import mysql.connector
passfile = open('/run/secrets/db-password', 'r')
class DBManager:
#give db some time to start def __init__(self, database='example', host="db", user="root", password_file=None):
time.sleep(5) pf = open(password_file, 'r')
self.connection = mysql.connector.connect(
#connect to db user=user,
conn = mysql.connector.connect( password=pf.read(),
user='root', host=host, # name of the mysql service as set in the docker-compose file
password=passfile.read(), database=database,
host='db', # name of the mysql service as set in the docker-compose file auth_plugin='mysql_native_password'
database='example', )
auth_plugin='mysql_native_password' pf.close()
) self.cursor = self.connection.cursor()
passfile.close() def populate_db(self):
# populate db self.cursor.execute('DROP TABLE IF EXISTS blog')
cursor = conn.cursor() self.cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))')
def prepare_db(): self.cursor.executemany('INSERT INTO blog (id, title) VALUES (%s, %s);', [(i, 'Blog post #%d'% i) for i in range (1,5)])
cursor.execute('DROP TABLE IF EXISTS blog') self.connection.commit()
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)]) def query_titles(self):
conn.commit() self.cursor.execute('SELECT title FROM blog')
prepare_db() rec = []
for c in self.cursor:
# server rec.append(c[0])
app = Flask(__name__) return rec
@app.route('/')
server = Flask(__name__)
conn = None
@server.route('/')
def listBlog(): 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 = '' response = ''
for c in cursor: for c in rec:
response = response + '<div>' + c[0] + '</div>' response = response + '<div> Hello ' + c + '</div>'
return response return response
if __name__ == '__main__': if __name__ == '__main__':
app.run() server.run()

Loading…
Cancel
Save