65 lines
1.8 KiB
Python
65 lines
1.8 KiB
Python
from flask import Flask, request, jsonify
|
|
import mysql.connector
|
|
import os
|
|
|
|
app = Flask(__name__)
|
|
|
|
DB_CFG = {
|
|
"host": os.getenv("DBHOST", "db"),
|
|
"user": os.getenv("DBUSER", "monitor_user"),
|
|
"password": os.getenv("DBPASS", "monitor_pass"),
|
|
"database": os.getenv("DBNAME", "webmonitor"),
|
|
}
|
|
|
|
def init_db():
|
|
conn = mysql.connector.connect(
|
|
host=DB_CFG["host"],
|
|
user=DB_CFG["user"],
|
|
password=DB_CFG["password"]
|
|
)
|
|
cur = conn.cursor()
|
|
cur.execute(f"CREATE DATABASE IF NOT EXISTS {DB_CFG['database']}")
|
|
conn.database = DB_CFG["database"]
|
|
cur.execute(f"""
|
|
CREATE TABLE IF NOT EXISTS status_log (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
timestamp VARCHAR(30) NOT NULL,
|
|
label VARCHAR(100) NOT NULL,
|
|
http_code INT NOT NULL
|
|
)
|
|
""")
|
|
conn.commit()
|
|
cur.close()
|
|
conn.close()
|
|
|
|
@app.route("/api/log", methods=["POST"])
|
|
def log_status():
|
|
data = request.get_json(force=True)
|
|
if not all(k in data for k in ("timestamp", "label", "http_code")):
|
|
return jsonify({"error": "invalid payload"}), 400
|
|
|
|
conn = mysql.connector.connect(**DB_CFG)
|
|
cur = conn.cursor()
|
|
cur.execute(
|
|
f"INSERT INTO status_log (timestamp,label,http_code) VALUES (%s,%s,%s)",
|
|
(data["timestamp"], data["label"], data["http_code"]),
|
|
)
|
|
conn.commit()
|
|
cur.close()
|
|
conn.close()
|
|
return jsonify({"status": "ok"}), 201
|
|
|
|
@app.route("/api/status", methods=["GET"])
|
|
def get_status():
|
|
conn = mysql.connector.connect(**DB_CFG)
|
|
cur = conn.cursor(dictionary=True)
|
|
cur.execute("SELECT * FROM status_log ORDER BY id DESC LIMIT 50")
|
|
rows = cur.fetchall()
|
|
cur.close()
|
|
conn.close()
|
|
return jsonify(rows)
|
|
|
|
if __name__ == "__main__":
|
|
init_db()
|
|
app.run(host="0.0.0.0", port=5000)
|