Skip to content

Commit

Permalink
Merge pull request #928 from to-sta/wait_for_db
Browse files Browse the repository at this point in the history
added custom management command wait_for_db
  • Loading branch information
andrewtavis authored Jul 7, 2024
2 parents 4df5e4b + 0154393 commit f2616b5
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 1 deletion.
Empty file.
Empty file.
39 changes: 39 additions & 0 deletions backend/backend/management/commands/wait_for_db.py
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)
1 change: 1 addition & 0 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"backend",
"authentication",
"entities",
"content",
Expand Down
1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ exclude = [
"entities/factories.py",
"events/factories.py",
]
enable_incomplete_feature = ["Unpack"]

[[tool.mypy.overrides]]
module = ["authentication.*", "content.*", "entities.*", "events.*"]
Expand Down
3 changes: 2 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ services:
context: ./backend
container_name: django_backend
restart: unless-stopped
command: sh -c "python manage.py makemigrations &&
command: sh -c "python manage.py wait_for_db &&
python manage.py makemigrations &&
python manage.py migrate &&
python manage.py loaddata fixtures/superuser.json &&
python manage.py loaddata fixtures/status_types.json &&
Expand Down

0 comments on commit f2616b5

Please sign in to comment.