hwdocker/web/app.py

71 lines
2 KiB
Python
Raw Normal View History

2024-11-23 15:45:35 +00:00
# ./web/app.py
2024-11-23 14:00:50 +00:00
from flask import Flask, jsonify
import pymysql
import os
2024-11-23 15:45:35 +00:00
import logging
import time
2024-11-23 14:00:50 +00:00
app = Flask(__name__)
2024-11-23 15:45:35 +00:00
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
2024-11-23 14:00:50 +00:00
def get_db_connection():
2024-11-23 15:45:35 +00:00
try:
connection = pymysql.connect(
host='db',
user=os.getenv('MYSQL_USER'),
password=os.getenv('MYSQL_PASSWORD'),
db=os.getenv('MYSQL_DATABASE')
)
logger.info("Connected to the database.")
return connection
except pymysql.MySQLError as e:
logger.error(f"Database connection failed: {e}")
return None
def wait_for_file(file_path):
logger.info(f"Waiting for the file: {file_path} to exist...")
while not os.path.isfile(file_path):
logger.debug("File not found, sleeping for 1 second...")
time.sleep(1)
logger.info("Signal file detected, proceeding...")
@app.route('/health')
def health():
# Check if the application can connect to the database
conn = get_db_connection()
if conn:
logger.info("Application is healthy.")
return jsonify({"status": "OK"}), 200
else:
logger.warning("Application health check failed.")
return jsonify({"status": "FAIL"}), 500
2024-11-23 14:00:50 +00:00
@app.route('/')
def index():
conn = get_db_connection()
2024-11-23 15:45:35 +00:00
if conn:
with conn.cursor() as cursor:
cursor.execute("SELECT name, age FROM data")
result = cursor.fetchall()
logger.info("Data queried successfully.")
else:
logger.error("Failed to fetch data due to database connection error.")
return jsonify({"error": "Database connection failed"}), 500
2024-11-23 14:00:50 +00:00
2024-11-23 15:45:35 +00:00
return jsonify(result), 200
2024-11-23 14:00:50 +00:00
@app.errorhandler(404)
def not_found(e):
2024-11-23 15:45:35 +00:00
logger.warning("404 error encountered.")
2024-11-23 14:00:50 +00:00
return jsonify({"error": "Not found"}), 404
2024-11-23 15:45:35 +00:00
if __name__ == "__main__":
signal_file_path = "/shared/data_filled.signal"
wait_for_file(signal_file_path)
app.run(host='0.0.0.0', port=8000)