Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import sqlite3
- from fastapi import FastAPI
- from fastapi.responses import HTMLResponse
- from pydantic import BaseModel
- app = FastAPI()
- DB_FILE = "db.sqlite"
- class ReportData(BaseModel):
- fecha: str
- usuario: str
- host: str
- kernel: str
- ultima_actualizacion: str
- sistema: dict
- def init_db():
- conn = sqlite3.connect(DB_FILE)
- cursor = conn.cursor()
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS reports (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- fecha TEXT,
- usuario TEXT,
- host TEXT,
- kernel TEXT,
- ultima_actualizacion TEXT,
- sistema TEXT
- )
- """)
- conn.commit()
- conn.close()
- @app.on_event("startup")
- def startup():
- init_db()
- @app.get("/", response_class=HTMLResponse)
- def root():
- conn = sqlite3.connect(DB_FILE)
- cursor = conn.cursor()
- cursor.execute("""
- SELECT
- id,
- fecha,
- usuario,
- host,
- kernel,
- ultima_actualizacion,
- sistema
- FROM reports
- """)
- rows = cursor.fetchall()
- conn.close()
- html = "<h1>Reports</h1><table border='1'>"
- html += """
- <tr>
- <th>id</th>
- <th>fecha</th>
- <th>usuario</th>
- <th>host</th>
- <th>kernel</th>
- <th>ultima_actualizacion</th>
- <th>sistema</th>
- </tr>
- """
- for row in rows:
- html += "<tr>" + "".join(f"<td>{col}</td>" for col in row) + "</tr>"
- html += "</table>"
- return html
- @app.post("/reports")
- def save_report(report: ReportData):
- conn = sqlite3.connect(DB_FILE)
- cursor = conn.cursor()
- cursor.execute("""
- INSERT INTO reports (
- fecha,
- usuario,
- host,
- kernel,
- ultima_actualizacion,
- sistema
- ) VALUES (?, ?, ?, ?, ?, ?)
- """, (
- report.fecha,
- report.usuario,
- report.host,
- report.kernel,
- report.ultima_actualizacion,
- json.dumps(report.sistema)
- ))
- conn.commit()
- conn.close()
- return {"message": "saved"}
Advertisement
Add Comment
Please, Sign In to add comment