django wait for database
import time
import sys
from django.db import OperationalError, connections
def write(message):
sys.stderr.write(message)
sys.stderr.flush()
def database_ready(database: str = "default", maximum_wait: int = 15) -> bool:
write("waiting for database...")
connected, start = False, time.time()
while not connected and time.time() - start < maximum_wait:
try:
connections[database].cursor().execute("SELECT 1")
connected = True
except OperationalError:
write("waiting for database...")
time.sleep(maximum_wait // 3)
if time.time() - start > maximum_wait:
raise OperationalError("Could not connect to database.")
return connected
# myproject/wsgi.py & asgi.py
"""
Wait for the default database to be ready before loading the application
"""
import os
from django.core.wsgi import get_wsgi_application
import utils
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
utils.database_ready("default", maximum_wait=15)
application = get_wsgi_application()
# myproject/management/commands/migrate.py
"""
Wait for the default database to bre ready before running migrations
"""
from django.core.management.commands.migrate import Command
from corrdyn_creds import utils
class Command(Command):
def handle(self, *args, **options):
utils.database_ready("default", maximum_wait=15)
super().handle(*args, **options)