55
66import requests
77from django .conf import settings
8+ from django .core .cache import cache
89from django .core .management .base import BaseCommand , CommandParser
910from django .db import connections
1011from django .db .utils import OperationalError
12+ from redis .exceptions import ConnectionError as RedisConnectionError
1113
1214
1315class TimeoutException (Exception ): ...
@@ -37,6 +39,25 @@ def wait_for_db(self):
3739
3840 self .stdout .write (self .style .SUCCESS (f"DB is available after { time .time () - start_time } seconds" ))
3941
42+ def wait_for_redis (self ):
43+ self .stdout .write ("Waiting for Redis..." )
44+ redis_conn = None
45+ start_time = time .time ()
46+ while True :
47+ try :
48+ cache .set ("wait-for-it-ping" , "pong" , timeout = 1 ) # Set a key to check Redis availability
49+ redis_conn = cache .get ("wait-for-it-ping" ) # Try to get the value back from Redis
50+ if redis_conn != "pong" :
51+ raise TypeError
52+ break
53+ except (RedisConnectionError , TypeError ):
54+ ...
55+ # Try again
56+ self .stdout .write (self .style .WARNING ("Redis not available, waiting..." ))
57+ time .sleep (1 )
58+
59+ self .stdout .write (self .style .SUCCESS (f"Redis is available after { time .time () - start_time } seconds" ))
60+
4061 def wait_for_minio (self ):
4162 self .stdout .write ("Waiting for Minio..." )
4263 AWS_S3_CONFIG_OPTIONS = getattr (settings , "AWS_S3_CONFIG_OPTIONS" , None ) or {}
@@ -69,6 +90,8 @@ def add_arguments(self, parser: CommandParser):
6990 help = "The maximum time (in seconds) the command is allowed to run before timing out. Default is 10 min." ,
7091 )
7192 parser .add_argument ("--db" , action = "store_true" , help = "Wait for DB to be available" )
93+ parser .add_argument ("--celery-queue" , action = "store_true" , help = "Wait for Celery queue to be available" )
94+ parser .add_argument ("--redis" , action = "store_true" , help = "Wait for Redis to be available" )
7295 parser .add_argument ("--minio" , action = "store_true" , help = "Wait for MinIO (S3) storage to be available" )
7396 parser .add_argument ("--all" , action = "store_true" , help = "Wait for all to be available" )
7497
@@ -86,6 +109,10 @@ def handle(self, **kwargs: typing.Any):
86109 self .wait_for_db ()
87110 if _all or kwargs ["minio" ]:
88111 self .wait_for_minio ()
112+ if _all or kwargs ["redis" ]:
113+ self .wait_for_redis ()
114+ if _all or kwargs ["celery_queue" ]:
115+ self .wait_for_redis ()
89116 except TimeoutException :
90117 ...
91118 finally :
0 commit comments