sergio_educacionit

fasta api sistema sever

Aug 8th, 2026
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import json
  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 ReportData(BaseModel):
  14. fecha: str
  15. usuario: str
  16. host: str
  17. kernel: str
  18. ultima_actualizacion: str
  19. sistema: dict
  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 reports (
  28. id INTEGER PRIMARY KEY AUTOINCREMENT,
  29. fecha TEXT,
  30. usuario TEXT,
  31. host TEXT,
  32. kernel TEXT,
  33. ultima_actualizacion TEXT,
  34. sistema 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. fecha,
  56. usuario,
  57. host,
  58. kernel,
  59. ultima_actualizacion,
  60. sistema
  61. FROM reports
  62. """)
  63.  
  64. rows = cursor.fetchall()
  65. conn.close()
  66.  
  67. html = "<h1>Reports</h1><table border='1'>"
  68. html += """
  69. <tr>
  70. <th>id</th>
  71. <th>fecha</th>
  72. <th>usuario</th>
  73. <th>host</th>
  74. <th>kernel</th>
  75. <th>ultima_actualizacion</th>
  76. <th>sistema</th>
  77. </tr>
  78. """
  79.  
  80. for row in rows:
  81. html += "<tr>" + "".join(f"<td>{col}</td>" for col in row) + "</tr>"
  82.  
  83. html += "</table>"
  84.  
  85. return html
  86.  
  87.  
  88. @app.post("/reports")
  89. def save_report(report: ReportData):
  90. conn = sqlite3.connect(DB_FILE)
  91. cursor = conn.cursor()
  92.  
  93. cursor.execute("""
  94. INSERT INTO reports (
  95. fecha,
  96. usuario,
  97. host,
  98. kernel,
  99. ultima_actualizacion,
  100. sistema
  101. ) VALUES (?, ?, ?, ?, ?, ?)
  102. """, (
  103. report.fecha,
  104. report.usuario,
  105. report.host,
  106. report.kernel,
  107. report.ultima_actualizacion,
  108. json.dumps(report.sistema)
  109. ))
  110.  
  111. conn.commit()
  112. conn.close()
  113.  
  114. return {"message": "saved"}
Advertisement
Add Comment
Please, Sign In to add comment