sergio_educacionit

monitor_server app

May 18th, 2026
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. ```python
  2. import sqlite3
  3. from fastapi import FastAPI
  4. from fastapi.responses import HTMLResponse
  5. from pydantic import BaseModel
  6.  
  7.  
  8. app = FastAPI()
  9.  
  10. DB_FILE = "db.sqlite"
  11.  
  12.  
  13. class ServerData(BaseModel):
  14. timestamp: int
  15. static_hostname: str
  16. machine_id: str
  17. operating_system: str
  18. uptime: str
  19. used_disk: str
  20.  
  21.  
  22. def init_db():
  23. conn = sqlite3.connect(DB_FILE)
  24. cursor = conn.cursor()
  25.  
  26. cursor.execute("""
  27. CREATE TABLE IF NOT EXISTS servers (
  28. id INTEGER PRIMARY KEY AUTOINCREMENT,
  29. timestamp INTEGER,
  30. static_hostname TEXT,
  31. machine_id TEXT UNIQUE,
  32. operating_system TEXT,
  33. uptime TEXT,
  34. used_disk TEXT
  35. )
  36. """)
  37.  
  38. conn.commit()
  39. conn.close()
  40.  
  41.  
  42. @app.on_event("startup")
  43. def startup():
  44. init_db()
  45.  
  46.  
  47. @app.get("/", response_class=HTMLResponse)
  48. def root():
  49. conn = sqlite3.connect(DB_FILE)
  50. cursor = conn.cursor()
  51.  
  52. cursor.execute("""
  53. SELECT
  54. id,
  55. timestamp,
  56. static_hostname,
  57. machine_id,
  58. operating_system,
  59. uptime,
  60. used_disk
  61. FROM servers
  62. """)
  63.  
  64. rows = cursor.fetchall()
  65.  
  66. conn.close()
  67.  
  68. html = "<h1>Servers List</h1><table border='1'>"
  69. html += """
  70. <tr>
  71. <th>id</th>
  72. <th>timestamp</th>
  73. <th>static_hostname</th>
  74. <th>machine_id</th>
  75. <th>operating_system</th>
  76. <th>uptime</th>
  77. <th>used_disk</th>
  78. </tr>
  79. """
  80.  
  81. for row in rows:
  82. html += "<tr>" + "".join(f"<td>{col}</td>" for col in row) + "</tr>"
  83.  
  84. html += "</table>"
  85.  
  86. return html
  87.  
  88.  
  89. @app.post("/servers")
  90. def save_server(server: ServerData):
  91. conn = sqlite3.connect(DB_FILE)
  92. cursor = conn.cursor()
  93.  
  94. cursor.execute("""
  95. INSERT INTO servers (
  96. timestamp,
  97. static_hostname,
  98. machine_id,
  99. operating_system,
  100. uptime,
  101. used_disk
  102. ) VALUES (?, ?, ?, ?, ?, ?)
  103. ON CONFLICT(machine_id) DO UPDATE SET
  104. timestamp = excluded.timestamp,
  105. static_hostname = excluded.static_hostname,
  106. operating_system = excluded.operating_system,
  107. uptime = excluded.uptime,
  108. used_disk = excluded.used_disk
  109. """, (
  110. server.timestamp,
  111. server.static_hostname,
  112. server.machine_id,
  113. server.operating_system,
  114. server.uptime,
  115. server.used_disk
  116. ))
  117.  
  118. conn.commit()
  119. conn.close()
  120.  
  121. return {"message": "saved"}
  122. ```
  123.  
Advertisement
Add Comment
Please, Sign In to add comment