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.

35 lines
1.1 KiB

  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(
  21. attempt=retry + 1,
  22. max_retries=max_retries,
  23. error=ex))
  24. time.sleep(poll_seconds)
  25. else:
  26. break
  27. else:
  28. self.stdout.write(self.style.ERROR('Database unavailable'))
  29. sys.exit(1)