Skip to content

Instantly share code, notes, and snippets.

@spumer
Created April 18, 2021 12:16
Show Gist options
  • Save spumer/a9853144367e41903dfb306c00118624 to your computer and use it in GitHub Desktop.
Save spumer/a9853144367e41903dfb306c00118624 to your computer and use it in GitHub Desktop.
django_wait_db_command
import logging
import time
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from django.db import connections
from django.db.utils import OperationalError
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Wait db become available'
def handle(self, *args, **options):
self.stdout.write('Waiting for database...')
timeout = int(options.get('timeout', 10))
ready = False
start = time.perf_counter()
while not ready:
try:
db_conn = connections['default']
c = db_conn.cursor()
c.execute('SELECT 1')
ready = c.fetchone()[0]
except OperationalError as exc:
if time.perf_counter() - start > timeout:
logger.exception('Database unavailable after %s seconds', timeout)
raise CommandError(f'Database unavailable after {timeout} seconds: {exc}', returncode=1)
self.stdout.write('Database unavailable, waiting 1 second...')
time.sleep(1)
self.stdout.write(self.style.SUCCESS('Database available!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment