hello.py 1019 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import os
  2. import time
  3. from flask import Flask
  4. import mysql.connector
  5. passfile = open('/run/secrets/db-password', 'r')
  6. #give db some time to start
  7. time.sleep(3)
  8. #connect to db
  9. conn = mysql.connector.connect(
  10. user='root',
  11. password=passfile.read(),
  12. host='db', # name of the mysql service as set in the docker-compose file
  13. database='example',
  14. auth_plugin='mysql_native_password'
  15. )
  16. passfile.close()
  17. cursor = conn.cursor()
  18. app = Flask(__name__)
  19. @app.route('/')
  20. def listBlog():
  21. cursor.execute('SELECT title FROM blog')
  22. response = ''
  23. for c in cursor:
  24. response = response + '<div>' + c[0] + '</div>'
  25. return response
  26. def prepare_db():
  27. cursor.execute('DROP TABLE IF EXISTS blog')
  28. cursor.execute('CREATE TABLE blog (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))')
  29. cursor.executemany('INSERT INTO blog (id, title) VALUES (%s, %s);', [(i, 'Blog post #%d'% i) for i in range (1,5)])
  30. conn.commit()
  31. if __name__ == '__main__':
  32. prepare_db()
  33. app.run()