celeryworker_pre_start.py 773 B

123456789101112131415161718192021222324252627282930313233343536
  1. import logging
  2. from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
  3. from db.session import db_session
  4. logging.basicConfig(level=logging.INFO)
  5. logger = logging.getLogger(__name__)
  6. max_tries = 60 * 5 # 5 minutes
  7. wait_seconds = 1
  8. @retry(
  9. stop=stop_after_attempt(max_tries),
  10. wait=wait_fixed(wait_seconds),
  11. before=before_log(logger, logging.INFO),
  12. after=after_log(logger, logging.WARN),
  13. )
  14. def init():
  15. try:
  16. # Try to create session to check if DB is awake
  17. db_session.execute("SELECT 1")
  18. except Exception as e:
  19. logger.error(e)
  20. raise e
  21. def main():
  22. logger.info("Initializing service")
  23. init()
  24. logger.info("Service finished initializing")
  25. if __name__ == "__main__":
  26. main()