Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```python
- import sqlite3
- from fastapi import FastAPI
- from fastapi.responses import HTMLResponse
- from pydantic import BaseModel
- app = FastAPI()
- DB_FILE = "db.sqlite"
- class ServerData(BaseModel):
- timestamp: int
- static_hostname: str
- machine_id: str
- operating_system: str
- uptime: str
- used_disk: 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,
- timestamp INTEGER,
- static_hostname TEXT,
- machine_id TEXT UNIQUE,
- operating_system TEXT,
- uptime TEXT,
- used_disk 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,
- timestamp,
- static_hostname,
- machine_id,
- operating_system,
- uptime,
- used_disk
- FROM servers
- """)
- rows = cursor.fetchall()
- conn.close()
- html = "<h1>Servers List</h1><table border='1'>"
- html += """
- <tr>
- <th>id</th>
- <th>timestamp</th>
- <th>static_hostname</th>
- <th>machine_id</th>
- <th>operating_system</th>
- <th>uptime</th>
- <th>used_disk</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 (
- timestamp,
- static_hostname,
- machine_id,
- operating_system,
- uptime,
- used_disk
- ) VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT(machine_id) DO UPDATE SET
- timestamp = excluded.timestamp,
- static_hostname = excluded.static_hostname,
- operating_system = excluded.operating_system,
- uptime = excluded.uptime,
- used_disk = excluded.used_disk
- """, (
- server.timestamp,
- server.static_hostname,
- server.machine_id,
- server.operating_system,
- server.uptime,
- server.used_disk
- ))
- conn.commit()
- conn.close()
- return {"message": "saved"}
- ```
Advertisement
Add Comment
Please, Sign In to add comment