69 lines
2 KiB
Python
69 lines
2 KiB
Python
from flask import Flask, jsonify
|
|
import pymysql
|
|
import os
|
|
import logging
|
|
import time
|
|
|
|
app = Flask(__name__)
|
|
|
|
# Configure logging
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def get_db_connection():
|
|
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
|
|
|
|
@app.route('/')
|
|
def index():
|
|
conn = get_db_connection()
|
|
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
|
|
|
|
return jsonify(result), 200
|
|
|
|
@app.errorhandler(404)
|
|
def not_found(e):
|
|
logger.warning("404 error encountered.")
|
|
return jsonify({"error": "Not found"}), 404
|
|
|
|
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)
|