Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sqlite3
- from fastapi import FastAPI
- from fastapi.responses import HTMLResponse
- from pydantic import BaseModel
- app = FastAPI()
- DB_FILE = "db.sqlite"
- class ServerData(BaseModel):
- static_hostname: str
- icon_name: str
- chassis: str
- machine_id: str
- boot_id: str
- virtualization: str
- operating_system: str
- kernel: str
- architecture: str
- hardware_vendor: str
- hardware_model: str
- firmware_version: str
- firmware_date: str
- firmware_age: str
- def init_db():
- conn = sqlite3.connect(DB_FILE)
- cursor = conn.cursor()
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS servers (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- static_hostname TEXT,
- icon_name TEXT,
- chassis TEXT,
- machine_id TEXT UNIQUE,
- boot_id TEXT,
- virtualization TEXT,
- operating_system TEXT,
- kernel TEXT,
- architecture TEXT,
- hardware_vendor TEXT,
- hardware_model TEXT,
- firmware_version TEXT,
- firmware_date TEXT,
- firmware_age 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 * FROM servers")
- rows = cursor.fetchall()
- conn.close()
- html = "<h1>Servers List</h1><table border='1'>"
- html += "<tr><th>id</th><th>static_hostname</th><th>icon_name</th><th>chassis</th><th>machine_id</th><th>boot_id</th><th>virtualization</th><th>operating_system</th><th>kernel</th><th>architecture</th><th>hardware_vendor</th><th>hardware_model</th><th>firmware_version</th><th>firmware_date</th><th>firmware_age</th></tr>"
- for row in rows:
- html += "<tr>" + "".join(f"<td>{col}</td>" for col in row) + "</tr>"
- html += "</table>"
- return html
- @app.post("/servers")
- def save_server(server: ServerData):
- conn = sqlite3.connect(DB_FILE)
- cursor = conn.cursor()
- cursor.execute("""
- INSERT INTO servers (
- static_hostname,
- icon_name,
- chassis,
- machine_id,
- boot_id,
- virtualization,
- operating_system,
- kernel,
- architecture,
- hardware_vendor,
- hardware_model,
- firmware_version,
- firmware_date,
- firmware_age
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- server.static_hostname,
- server.icon_name,
- server.chassis,
- server.machine_id,
- server.boot_id,
- server.virtualization,
- server.operating_system,
- server.kernel,
- server.architecture,
- server.hardware_vendor,
- server.hardware_model,
- server.firmware_version,
- server.firmware_date,
- server.firmware_age
- ))
- conn.commit()
- conn.close()
- return {"message": "saved"}
Advertisement
Add Comment
Please, Sign In to add comment