hello.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. from flask import Flask
  3. import mysql.connector
  4. class DBManager:
  5. def __init__(self, database='example', host="db", user="root", password_file=None):
  6. pf = open(password_file, 'r')
  7. self.connection = mysql.connector.connect(
  8. user=user,
  9. password=pf.read(),
  10. host=host, # name of the mysql service as set in the docker compose file
  11. database=database,
  12. auth_plugin='mysql_native_password'
  13. )
  14. pf.close()
  15. self.cursor = self.connection.cursor()
  16. def populate_db(self):
  17. self.cursor.execute('DROP TABLE IF EXISTS blog')
  18. self.cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))')
  19. self.cursor.executemany('INSERT INTO blog (id, title) VALUES (%s, %s);', [(i, 'Blog post #%d'% i) for i in range (1,5)])
  20. self.connection.commit()
  21. def query_titles(self):
  22. self.cursor.execute('SELECT title FROM blog')
  23. rec = []
  24. for c in self.cursor:
  25. rec.append(c[0])
  26. return rec
  27. server = Flask(__name__)
  28. conn = None
  29. @server.route('/')
  30. def listBlog():
  31. global conn
  32. if not conn:
  33. conn = DBManager(password_file='/run/secrets/db-password')
  34. conn.populate_db()
  35. rec = conn.query_titles()
  36. response = ''
  37. for c in rec:
  38. response = response + '<div> Hello ' + c + '</div>'
  39. return response
  40. if __name__ == '__main__':
  41. server.run()