health.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from flask import current_app
  2. from flask_classful import FlaskView, route
  3. from flask_json import as_json
  4. import sqlalchemy as sa
  5. from redis.exceptions import ConnectionError
  6. from flexmeasures.data import db
  7. def _check_sql_database():
  8. try:
  9. db.session.execute(sa.text("SELECT 1")).first()
  10. return True
  11. except Exception: # noqa: B902
  12. current_app.logger.exception("Database down or undetected")
  13. return False
  14. def _check_redis() -> bool:
  15. """Check status of the redis instance
  16. :return: True if the redis instance is active, False otherwise
  17. """
  18. try:
  19. current_app.redis_connection.ping()
  20. return True
  21. except ConnectionError:
  22. return False
  23. class HealthAPI(FlaskView):
  24. route_base = "/health"
  25. trailing_slash = False
  26. @route("/ready", methods=["GET"])
  27. @as_json
  28. def is_ready(self):
  29. """
  30. Get readiness status
  31. .. :quickref: Health; Get readiness status
  32. **Example response:**
  33. .. sourcecode:: json
  34. {
  35. 'database_sql': True,
  36. 'database_redis': False
  37. }
  38. """
  39. status = {
  40. "database_sql": _check_sql_database(),
  41. }
  42. if current_app.config.get("FLEXMEASURES_REDIS_PASSWORD") is not None:
  43. status["database_redis"] = _check_redis()
  44. if all(status.values()):
  45. return status, 200
  46. else:
  47. return status, 503