Created
March 9, 2024 10:56
-
-
Save enzofrnt/8561254766c8e3ab45d5139128bae2fb to your computer and use it in GitHub Desktop.
Django command to wait for database availability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from django.db import connections | |
from django.db.utils import OperationalError | |
from django.core.management.base import BaseCommand | |
from django.db import DEFAULT_DB_ALIAS | |
class Command(BaseCommand): | |
"""Django command to pause execution until database is available""" | |
def handle(self, *args, **options): | |
"""Handle the command""" | |
self.stdout.write('Waiting for database...') | |
while True: | |
try: | |
db_conn = connections[DEFAULT_DB_ALIAS] | |
db_conn.ensure_connection() | |
self.stdout.write(self.style.SUCCESS('Database available!')) | |
break # Sortie de la boucle si la connexion est réussie | |
except OperationalError: | |
self.stdout.write('Database unavailable, waiting 1 second...') | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment