import logging from django.http import HttpResponse from django.db import connections from django.db.utils import OperationalError logger = logging.getLogger(__name__) class HealthCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path == "/health": db_conn = connections["default"] try: c = db_conn.cursor() except OperationalError: is_db_connected = False else: is_db_connected = True logger.info( "[health-check]", extra={"is_db_connected": is_db_connected} ) if is_db_connected: return HttpResponse("ok") return self.get_response(request)