# health/views.py
from django.db import connection
from django.core.cache import cache
from django.http import JsonResponse
def health(request):
checks = {}
try:
with connection.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
checks["db"] = True
except Exception as e:
checks["db"] = False
checks["db_error"] = str(e)[:80]
try:
cache.set("__health", 1, 5)
checks["cache"] = cache.get("__health") == 1
except Exception:
checks["cache"] = False
ok = all(v is True for k, v in checks.items() if not k.endswith("_error"))
return JsonResponse(
{"status": "ok" if ok else "degraded", "checks": checks},
status=200 if ok else 503,
)
# urls.py
# path("health/", views.health)