Improved flask backend
This commit is contained in:
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')
|
|
||||||
|
|
||||||
#give db some time to start
|
class DBManager:
|
||||||
time.sleep(5)
|
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()
|
||||||
|
|
||||||
#connect to db
|
def populate_db(self):
|
||||||
conn = mysql.connector.connect(
|
self.cursor.execute('DROP TABLE IF EXISTS blog')
|
||||||
user='root',
|
self.cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))')
|
||||||
password=passfile.read(),
|
self.cursor.executemany('INSERT INTO blog (id, title) VALUES (%s, %s);', [(i, 'Blog post #%d'% i) for i in range (1,5)])
|
||||||
host='db', # name of the mysql service as set in the docker-compose file
|
self.connection.commit()
|
||||||
database='example',
|
|
||||||
auth_plugin='mysql_native_password'
|
|
||||||
)
|
|
||||||
|
|
||||||
passfile.close()
|
def query_titles(self):
|
||||||
# populate db
|
self.cursor.execute('SELECT title FROM blog')
|
||||||
cursor = conn.cursor()
|
rec = []
|
||||||
def prepare_db():
|
for c in self.cursor:
|
||||||
cursor.execute('DROP TABLE IF EXISTS blog')
|
rec.append(c[0])
|
||||||
cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))')
|
return rec
|
||||||
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__)
|
server = Flask(__name__)
|
||||||
@app.route('/')
|
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…
Reference in New Issue
Block a user