database.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Admin database overview, health checks and log import API."""
  2. import os
  3. import tempfile
  4. from flask import jsonify, render_template, request
  5. from flask_babel import gettext as _
  6. from loguru import logger
  7. from parsers.log import import_logs as import_log_file
  8. from services.auth.auth_service import (
  9. admin_required,
  10. api_admin_required,
  11. api_auth_required,
  12. )
  13. from services.database import backup_service
  14. from services.database.db_info_service import get_db_health, run_integrity_check
  15. from .helpers import json_error
  16. def register_routes(bp):
  17. @bp.route("/database")
  18. @admin_required
  19. def database_view():
  20. cfg = backup_service.load_config()
  21. return render_template("admin/database.html", current_config=cfg)
  22. @bp.route("/api/db-health", methods=["GET"])
  23. @api_auth_required
  24. def db_health():
  25. resp, code = get_db_health()
  26. return jsonify(resp), code
  27. @bp.route("/api/db-integrity", methods=["POST"])
  28. @api_auth_required
  29. def db_integrity():
  30. resp, code = run_integrity_check()
  31. return jsonify(resp), code
  32. @bp.route("/api/import-logs", methods=["POST"])
  33. @api_admin_required
  34. def import_logs():
  35. """Import an uploaded Squid access log into its daily tables."""
  36. uploaded_file = request.files.get("file")
  37. if not uploaded_file or not uploaded_file.filename:
  38. return json_error(_("Selecciona un archivo de logs para importar"))
  39. temporary_path = None
  40. try:
  41. with tempfile.NamedTemporaryFile(
  42. prefix="squidstats-log-import-",
  43. suffix=".log",
  44. delete=False,
  45. ) as temporary_file:
  46. temporary_path = temporary_file.name
  47. uploaded_file.save(temporary_file)
  48. summary = import_log_file(temporary_path)
  49. return jsonify(
  50. {
  51. "status": "success",
  52. "message": _("Importación completada correctamente"),
  53. "summary": summary,
  54. }
  55. )
  56. except FileNotFoundError:
  57. return json_error(_("No se pudo leer el archivo de logs"), 400)
  58. except ValueError:
  59. return json_error(_("El archivo no contiene logs de Squid válidos"), 400)
  60. except Exception:
  61. logger.exception("Error importing uploaded log file")
  62. return json_error(_("No se pudo importar el archivo de logs"), 500)
  63. finally:
  64. if temporary_path:
  65. try:
  66. os.unlink(temporary_path)
  67. except FileNotFoundError:
  68. pass