Skip to content

Instantly share code, notes, and snippets.

@enzofrnt
Created March 9, 2024 10:56
Show Gist options
  • Save enzofrnt/8561254766c8e3ab45d5139128bae2fb to your computer and use it in GitHub Desktop.
Save enzofrnt/8561254766c8e3ab45d5139128bae2fb to your computer and use it in GitHub Desktop.
Django command to wait for database availability
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)
@elOrlin
Copy link

elOrlin commented Jan 20, 2025

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.

@elOrlin
Copy link

elOrlin commented Jan 20, 2025

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!'))

`

@enzofrnt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment