Skip to content

Commit

Permalink
Handle database health check with Django
Browse files Browse the repository at this point in the history
  • Loading branch information
ulgens committed Sep 29, 2024
1 parent 2cf5f40 commit e742041
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
9 changes: 3 additions & 6 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ jobs:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
redis:
Expand Down Expand Up @@ -84,4 +79,6 @@ jobs:
CELERY_RESULT_BACKEND: ""
DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports[5432] }}/postgres
SECRET_KEY: ""
run: poetry run python manage.py test --parallel --shuffle
run: |
python run python manage.py wait_for_db
poetry run python manage.py test --parallel --shuffle
29 changes: 29 additions & 0 deletions src/core/management/commands/wait_for_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
Command to wait for the database to be available before proceeding.
Inspired from https://github.com/enzofrnt/django_wait_for_db
"""

import time

import djclick as click
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.utils import OperationalError


@click.command()
def wait_for_db():
click.secho("Waiting for the database to be available...", fg="yellow")

while True:
try:
db_conn = connections[DEFAULT_DB_ALIAS]
db_conn.ensure_connection()
click.secho("Database available!", fg="green")
break

except OperationalError as e:
click.secho(f"Error with database: {e}", fg="red")
click.secho("Database unavailable, waiting 1 second...", fg="yellow")

time.sleep(1)

0 comments on commit e742041

Please sign in to comment.