I am trying to have django asgi app exit when the database connection fails. Normal behaviour seems to be that the app and its endpoint happily keep running and are accessible even though the database connection has failed. I want the app to exit. I tried this in asgi.py but the app still persists when I deliberately have the database connection to fail. Any ideas?
import os
import django
import threading
from django.core.asgi import get_asgi_application
from django.db import connections
from django.db.utils import OperationalError
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SAFD.settings")
django.setup()
# Function to check database connection in a separate thread
def check_database_connection():
try:
connections['default'].cursor()
except OperationalError:
exit(1)
# raise Exception("Database connection failed")
# Synchronously check the database connection
db_check_thread = threading.Thread(target=check_database_connection)
db_check_thread.start()
db_check_thread.join()
# Create the ASGI application instance
django_asgi_app = get_asgi_application()
async def application(scope, receive, send):
await django_asgi_app(scope, receive, send)
In fact right now I would dare to say that the error handling in Django is not set up correctly. If the app runs without the db connection, you can happily reach your endpoints but get errors like 'Network error' instead of what the real problem is: 'Database error'