app.py aktualisiert
This commit is contained in:
101
app.py
101
app.py
@@ -1,65 +1,50 @@
|
|||||||
from flask import Flask, request, jsonify
|
from fastapi import FastAPI, HTTPException
|
||||||
import mysql.connector
|
from pydantic import BaseModel
|
||||||
import os
|
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 = {
|
engine = create_engine(DATABASE_URL)
|
||||||
"host": os.getenv("DBHOST", "db"),
|
SessionLocal = sessionmaker(bind=engine)
|
||||||
"user": os.getenv("DBUSER", "monitor_user"),
|
Base = declarative_base()
|
||||||
"password": os.getenv("DBPASS", "monitor_pass"),
|
|
||||||
"database": os.getenv("DBNAME", "webmonitor"),
|
|
||||||
"port": int(os.getenv("DBPORT", "3306")),
|
|
||||||
}
|
|
||||||
|
|
||||||
def init_db():
|
# Tabelle definieren
|
||||||
conn = mysql.connector.connect(
|
class Entry(Base):
|
||||||
host=DB_CFG["host"],
|
__tablename__ = "entries"
|
||||||
user=DB_CFG["user"],
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
password=DB_CFG["password"]
|
timestamp = Column(DateTime, default=datetime.utcnow)
|
||||||
)
|
name = Column(String(100))
|
||||||
cur = conn.cursor()
|
code = Column(String(100))
|
||||||
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"])
|
Base.metadata.create_all(bind=engine)
|
||||||
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)
|
# API definieren
|
||||||
cur = conn.cursor()
|
app = FastAPI()
|
||||||
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"])
|
class EntryCreate(BaseModel):
|
||||||
def get_status():
|
name: str
|
||||||
conn = mysql.connector.connect(**DB_CFG)
|
code: str
|
||||||
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__":
|
@app.post("/entries/")
|
||||||
init_db()
|
def create_entry(entry: EntryCreate):
|
||||||
app.run(host="0.0.0.0", port=5000)
|
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