Greatly simplified "wait_for_db" command

This commit is contained in:
Oliver Walters 2021-04-08 00:37:34 +10:00
parent 71cac6e269
commit 3926276fd1

View File

@ -4,10 +4,8 @@ Custom management command, wait for the database to be ready!
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.db import connections from django.db import connection
from django.db.utils import OperationalError from django.db.utils import OperationalError, ImproperlyConfigured
from part.models import Part
import time import time
@ -18,20 +16,27 @@ class Command(BaseCommand):
""" """
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
self.stdout.write("Waiting for database...") self.stdout.write("Waiting for database...")
db_conn = None connected = False
while not connected:
time.sleep(5)
while not db_conn:
try: try:
# get the database with keyword 'default' from settings.py connection.ensure_connection()
db_conn = connections['default']
# Try to read some data from the database connected = True
Part.objects.count()
# prints success messge in green except OperationalError as e:
self.stdout.write(self.style.SUCCESS('InvenTree database connected')) self.stdout.write(f"Could not connect to database: {e}")
except: except ImproperlyConfigured as e:
self.stdout.write(self.style.ERROR("Database unavailable, waiting 5 seconds ...")) self.stdout.write(f"Improperly configured: {e}")
time.sleep(5) else:
if not connection.is_usable():
self.stdout.write("Database configuration is not usable")
if connected:
self.stdout.write("Database connection sucessful!")