Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Created March 14, 2021 08:55
Show Gist options
  • Save aaronlab/91eb459239278a934662478f9d186da8 to your computer and use it in GitHub Desktop.
Save aaronlab/91eb459239278a934662478f9d186da8 to your computer and use it in GitHub Desktop.
Django: wait_for_db command
# https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command to pause execution till db is ready"""
def handle(self, *args, **options):
self.stdout.write('Waiting for db...')
db_conn = None
while not db_conn:
try:
db_conn = connections['default']
except OperationalError:
self.stdout.write('DB is not ready, waiting 1 sec...')
time.sleep(1)
self.stdout.write(self.style.SUCCESS('DB is ready!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment