Skip to content

Commit

Permalink
Handle cache 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 5c134ef commit e56ff26
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
6 changes: 1 addition & 5 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,6 @@ jobs:
image: redis:7.4.0-alpine3.20
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5

steps:
- uses: actions/checkout@v4.1.7
Expand Down Expand Up @@ -81,4 +76,5 @@ jobs:
SECRET_KEY: ""
run: |
poetry run python manage.py wait_for_db
poetry run python manage.py wait_for_cache
poetry run python manage.py test --parallel --shuffle
32 changes: 32 additions & 0 deletions src/core/management/commands/wait_for_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
Command to wait for the cache to be available before proceeding.
Inspired from https://github.com/enzofrnt/django_wait_for_db
"""

import time

import djclick as click
from django.core.cache import caches
from redis.exceptions import ConnectionError


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

while True:
try:
cache = caches["default"]
client = cache._cache.get_client()
client.ping()

click.secho("Cache available!", fg="green")

break

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

time.sleep(1)

0 comments on commit e56ff26

Please sign in to comment.