You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
1.1 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. import sys
  2. import time
  3. from django.core.management.base import BaseCommand
  4. from django.db import connection
  5. from django.db.utils import OperationalError
  6. class Command(BaseCommand):
  7. help = "Blocks until the database is available"
  8. def add_arguments(self, parser):
  9. parser.add_argument("--poll_seconds", type=float, default=3)
  10. parser.add_argument("--max_retries", type=int, default=60)
  11. def handle(self, *args, **options):
  12. max_retries = options["max_retries"]
  13. poll_seconds = options["poll_seconds"]
  14. for retry in range(max_retries):
  15. try:
  16. connection.ensure_connection()
  17. except OperationalError as ex:
  18. self.stdout.write(
  19. "Database unavailable on attempt {attempt}/{max_retries}:"
  20. " {error}".format(attempt=retry + 1, max_retries=max_retries, error=ex)
  21. )
  22. time.sleep(poll_seconds)
  23. else:
  24. break
  25. else:
  26. self.stdout.write(self.style.ERROR("Database unavailable"))
  27. sys.exit(1)