zkt25/z2/app.py

67 lines
2.2 KiB
Python

from flask import Flask, jsonify, send_from_directory
import mysql.connector
import os
import time
app = Flask(__name__, static_folder='.', static_url_path='')
# Database connection with environment variables
def get_db_connection():
# Get environment variables or use defaults
host = os.environ.get('MYSQL_HOST', 'mysql-service.sensor-app')
user = os.environ.get('MYSQL_USER', 'root')
password = os.environ.get('MYSQL_PASSWORD', '')
database = os.environ.get('MYSQL_DB', 'sensors_db')
print(f"Connecting to MySQL: {host}, {user}, {database}")
# Try to connect with retries for Kubernetes startup sequence
max_retries = 50
retry_delay = 50
for attempt in range(max_retries):
try:
conn = mysql.connector.connect(
host=host,
user=user,
password=password,
database=database
)
print("Database connection successful!")
return conn
except mysql.connector.Error as err:
print(f"Database connection error: {err}")
if attempt < max_retries - 1:
print(f"Database connection failed, retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
else:
print(f"Failed to connect to database after {max_retries} attempts")
raise
@app.route('/api/sensors', methods=['GET'])
def get_sensors():
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute('SELECT * FROM sensors')
sensors = cursor.fetchall()
cursor.close()
conn.close()
print(f"Sensors fetched from database: {sensors}")
return jsonify(sensors)
except Exception as e:
print(f"Error fetching sensors: {e}")
# Return empty array instead of error for better frontend handling
return jsonify([])
@app.route('/')
def index():
return send_from_directory('.', 'index.html')
# Serve static files
@app.route('/<path:path>')
def static_files(path):
return send_from_directory('.', path)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')