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 hidden or 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) |
It is always better to interact with variables that add the value directly as you do with the boolean.
"""
Django command to wait for the database to be available.
"""
`
import time
from psycopg2 import OperationalError as Psycopg2OpError
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
"""
Django command to wait for the database to be available.
"""
import time
from psycopg2 import OperationalError as Psycopg2OpError
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command to wait for database."""
def handle(self, *args, **options):
"""Entrypoint for command."""
self.stdout.write('Waiting for database...')
db_up = False
while db_up is False:
try:
self.check(databases=['default'])
db_up = True
except (Psycopg2OpError, OperationalError):
self.stdout.write('Database unavailable, waiting 1 second...')
time.sleep(1)
self.stdout.write(self.style.SUCCESS('Database available!'))
`
Hi @elOrlin, checkout this and make PR. ; )
https://github.com/enzofrnt/django_wait_for_db
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add another line when it database is available self.stdout.write(self.style.SUCCESS("Database available!")) in position with the bucle while and it will show this message when you run Database.