-
Notifications
You must be signed in to change notification settings - Fork 192
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #928 from to-sta/wait_for_db
added custom management command wait_for_db
- Loading branch information
Showing
6 changed files
with
43 additions
and
1 deletion.
There are no files selected for viewing
Empty file.
Empty file.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import sys | ||
import time | ||
from argparse import ArgumentParser | ||
from typing import TypedDict, Unpack | ||
|
||
from django.core.management.base import BaseCommand | ||
from django.db import connection | ||
from django.db.utils import OperationalError | ||
|
||
|
||
class Options(TypedDict): | ||
poll_seconds: float | ||
max_retries: int | ||
|
||
|
||
class Command(BaseCommand): | ||
help = "Wait until the database is available" | ||
|
||
def add_arguments(self, parser: ArgumentParser) -> None: | ||
parser.add_argument("--poll_seconds", type=float, default=2) | ||
parser.add_argument("--max_retries", type=int, default=30) | ||
|
||
def handle(self, *args: str, **options: Unpack[Options]) -> None: | ||
poll_seconds = options["poll_seconds"] | ||
max_retries = options["max_retries"] | ||
|
||
for retry in range(max_retries): | ||
try: | ||
connection.ensure_connection() | ||
except OperationalError as error: | ||
self.stdout.write( | ||
f"Database unavailable on attempt {retry + 1}/{max_retries}: {error}" | ||
) | ||
time.sleep(poll_seconds) | ||
else: | ||
break | ||
else: | ||
self.stdout.write(self.style.ERROR("Database unavailable")) | ||
sys.exit(1) |
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
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
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