app.py aktualisiert
This commit is contained in:
101
app.py
101
app.py
@@ -1,65 +1,50 @@
|
||||
from flask import Flask, request, jsonify
|
||||
import mysql.connector
|
||||
import os
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import create_engine, Column, Integer, String, DateTime
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from datetime import datetime
|
||||
|
||||
app = Flask(__name__)
|
||||
# Verbindung zur MariaDB
|
||||
DATABASE_URL = "mysql://mariadb:r5WdORhRYOajNZ9lcn1raCWpXAhQa1v6sM5xN8JEffr2rZLDhQvAGQVfcj6f7rzf@tkgo4k84c8wgcos40kgs8ows:3306/default"
|
||||
|
||||
DB_CFG = {
|
||||
"host": os.getenv("DBHOST", "db"),
|
||||
"user": os.getenv("DBUSER", "monitor_user"),
|
||||
"password": os.getenv("DBPASS", "monitor_pass"),
|
||||
"database": os.getenv("DBNAME", "webmonitor"),
|
||||
"port": int(os.getenv("DBPORT", "3306")),
|
||||
}
|
||||
engine = create_engine(DATABASE_URL)
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
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()
|
||||
# Tabelle definieren
|
||||
class Entry(Base):
|
||||
__tablename__ = "entries"
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
timestamp = Column(DateTime, default=datetime.utcnow)
|
||||
name = Column(String(100))
|
||||
code = Column(String(100))
|
||||
|
||||
@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
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
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
|
||||
# API definieren
|
||||
app = FastAPI()
|
||||
|
||||
@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)
|
||||
class EntryCreate(BaseModel):
|
||||
name: str
|
||||
code: str
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_db()
|
||||
app.run(host="0.0.0.0", port=5000)
|
||||
@app.post("/entries/")
|
||||
def create_entry(entry: EntryCreate):
|
||||
session = SessionLocal()
|
||||
db_entry = Entry(name=entry.name, code=entry.code)
|
||||
session.add(db_entry)
|
||||
try:
|
||||
session.commit()
|
||||
session.refresh(db_entry)
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
finally:
|
||||
session.close()
|
||||
return {
|
||||
"id": db_entry.id,
|
||||
"timestamp": db_entry.timestamp,
|
||||
"name": db_entry.name,
|
||||
"code": db_entry.code
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user