helpers.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """
  2. Shared helpers for admin route modules.
  3. Centralizes repetitive patterns: flash+redirect, debug detection,
  4. form field parsing, JSON error responses, and config_manager access.
  5. """
  6. from flask import current_app, flash, jsonify, redirect, request, url_for
  7. from loguru import logger
  8. from utils.admin import SquidConfigManager
  9. # ---------------------------------------------------------------------------
  10. # Config manager accessor (replaces global mutable)
  11. # ---------------------------------------------------------------------------
  12. def get_config_manager() -> SquidConfigManager:
  13. """Return the shared :class:`SquidConfigManager` instance.
  14. Stored on ``current_app`` so it lives for the app's lifetime without
  15. needing a module-level mutable global.
  16. """
  17. cm = getattr(current_app, "_squid_config_manager", None)
  18. if cm is None:
  19. cm = SquidConfigManager()
  20. current_app._squid_config_manager = cm
  21. return cm
  22. def reload_config_manager() -> SquidConfigManager:
  23. """Force-reload the :class:`SquidConfigManager` (e.g. after split)."""
  24. cm = SquidConfigManager()
  25. current_app._squid_config_manager = cm
  26. logger.info("Config manager reloaded")
  27. return cm
  28. # ---------------------------------------------------------------------------
  29. # Flash + Redirect helper
  30. # ---------------------------------------------------------------------------
  31. def flash_and_redirect(success: bool, message: str, endpoint: str, **kwargs):
  32. """Flash a message and redirect to *endpoint* in a single call."""
  33. flash(message, "success" if success else "error")
  34. return redirect(url_for(endpoint, **kwargs))
  35. # ---------------------------------------------------------------------------
  36. # Debug mode helper
  37. # ---------------------------------------------------------------------------
  38. def is_debug() -> bool:
  39. """Return ``True`` when the Flask app is running in debug mode.
  40. Safely handles the case where no application context is active.
  41. """
  42. try:
  43. return bool(current_app.debug)
  44. except RuntimeError:
  45. return False
  46. # ---------------------------------------------------------------------------
  47. # Form field parsing helpers
  48. # ---------------------------------------------------------------------------
  49. def get_int_form_field(name: str) -> int | None:
  50. """Parse an integer from ``request.form[name]``.
  51. Returns ``None`` when the value is missing or not a valid integer.
  52. """
  53. try:
  54. return int(request.form.get(name))
  55. except (ValueError, TypeError):
  56. return None
  57. # ---------------------------------------------------------------------------
  58. # JSON error response helpers
  59. # ---------------------------------------------------------------------------
  60. def json_error(message: str, status_code: int = 400, *, details: str | None = None):
  61. """Build a standard JSON error response.
  62. When the app is in debug mode and *details* is provided, the details
  63. are included in the payload.
  64. """
  65. resp = {"status": "error", "message": message}
  66. if is_debug() and details:
  67. resp["details"] = details
  68. return jsonify(resp), status_code
  69. def json_success(message: str, *, extra: dict | None = None):
  70. """Build a standard JSON success response."""
  71. resp = {"status": "success", "message": message}
  72. if extra:
  73. resp.update(extra)
  74. return jsonify(resp)
  75. # ---------------------------------------------------------------------------
  76. # Flash error with debug details
  77. # ---------------------------------------------------------------------------
  78. def flash_error_with_details(user_message: str, exception: Exception | None = None):
  79. """Flash an error message; include exception details in debug mode."""
  80. if is_debug() and exception is not None:
  81. flash(f"{user_message}: {exception}", "error")
  82. else:
  83. flash(user_message, "error")