MySQLStatus / app.py
Niansuh's picture
Create app.py
05d4c21 verified
from flask import Flask, jsonify
import mysql.connector
import os
from mysql.connector import Error
app = Flask(__name__)
# Get MySQL connection details from environment variables
MYSQL_HOST = os.getenv('MYSQL_HOST', 'localhost') # Default to localhost if not set
MYSQL_USER = os.getenv('MYSQL_USER', 'root')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD', 'password')
MYSQL_DB = os.getenv('MYSQL_DB', 'your_database') # Optional database name
@app.route('/mysql/status', methods=['GET'])
def check_mysql_status():
try:
# Try connecting to MySQL
connection = mysql.connector.connect(
host=MYSQL_HOST,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
database=MYSQL_DB
)
# If connection is successful, return status
if connection.is_connected():
return jsonify({
"status": "OK",
"message": "MySQL Server is up and running!",
"host": MYSQL_HOST
}), 200
else:
return jsonify({
"status": "Error",
"message": "Failed to connect to MySQL server."
}), 500
except Error as e:
return jsonify({
"status": "Error",
"message": f"Database connection failed: {str(e)}"
}), 500
finally:
if connection.is_connected():
connection.close()
if __name__ == '__main__':
# Run the app (make it accessible on all IPs, port 5000)
app.run(debug=True, host='0.0.0.0', port=5000)