sergio_educacionit

fastapi (user_space) main.py

Dec 5th, 2025 (edited)
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. from fastapi import FastAPI, Request
  2. from fastapi.responses import HTMLResponse
  3. import sqlite3
  4.  
  5. app = FastAPI()
  6.  
  7. # Crear base y tabla si no existen
  8. conn = sqlite3.connect("data.sqlite")
  9. cursor = conn.cursor()
  10. cursor.execute("""
  11. CREATE TABLE IF NOT EXISTS reportes (
  12. id INTEGER PRIMARY KEY AUTOINCREMENT,
  13. user TEXT,
  14. home TEXT,
  15. home_size TEXT
  16. )
  17. """)
  18. conn.commit()
  19. conn.close()
  20.  
  21. @app.post("/report")
  22. async def recibir_reporte(request: Request):
  23. data = await request.json()
  24. user = data.get("user", "")
  25. home = data.get("home", "")
  26. home_size = data.get("home_size", "")
  27.  
  28. conn = sqlite3.connect("data.sqlite")
  29. cursor = conn.cursor()
  30. cursor.execute("""
  31. INSERT INTO reportes (user, home, home_size)
  32. VALUES (?, ?, ?)
  33. """, (user, home, home_size))
  34. conn.commit()
  35. conn.close()
  36.  
  37. return {"mensaje": "Datos guardados en data.sqlite"}
  38.  
  39. @app.get("/", response_class=HTMLResponse)
  40. def ver_reportes():
  41. conn = sqlite3.connect("data.sqlite")
  42. cursor = conn.cursor()
  43. cursor.execute("SELECT user, home, home_size FROM reportes")
  44. filas = cursor.fetchall()
  45. conn.close()
  46.  
  47. html = """
  48. <html>
  49. <head><title>Reportes de usuarios</title></head>
  50. <body>
  51. <h2>Reportes guardados</h2>
  52. <table border="1" cellpadding="5">
  53. <tr><th>Usuario</th><th>Directorio</th><th>TamaƱo</th></tr>
  54. """
  55.  
  56. for fila in filas:
  57. html += f"<tr><td>{fila[0]}</td><td>{fila[1]}</td><td>{fila[2]}</td></tr>"
  58.  
  59. html += """
  60. </table>
  61. </body>
  62. </html>
  63. """
  64.  
  65. return html
  66.  
Advertisement
Add Comment
Please, Sign In to add comment