Skip to content

Commit

Permalink
Add a --command argument, allowing to directly call a Django command …
Browse files Browse the repository at this point in the history
…when databases are ready, without patching the command itself and without loading the django machinery twice.
  • Loading branch information
d9pouces committed Oct 8, 2023
1 parent 1b6d17f commit 3995f1e
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions django_probes/management/commands/wait_for_database.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""
Django management command ``wait_for_database``
"""
import shlex
import sys
from time import sleep, time

from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.utils import OperationalError
Expand Down Expand Up @@ -88,13 +90,20 @@ def add_arguments(self, parser):
help='which database of `settings.DATABASES` '
'to wait for. Defaults to the "default" '
'database.')
parser.add_argument("--command", "-c", default=None,
action="store", dest='command',
help='execute this command when database is up')

def handle(self, *args, **options):
"""
Wait for a database connection to come up. Exit with error
status when a timeout threshold is surpassed.
"""
command = options.pop("command", None)
try:
wait_for_database(**options)
except TimeoutError as err:
raise CommandError(err) from err
if command:
command_list = shlex.split(command)
call_command(command_list[0], *command_list[1:])

0 comments on commit 3995f1e

Please sign in to comment.