backend_pre_start.py 815 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import logging
  2. from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
  3. from app.db.session import SessionLocal
  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() -> None:
  15. try:
  16. db = SessionLocal()
  17. # Try to create session to check if DB is awake
  18. db.execute("SELECT 1")
  19. except Exception as e:
  20. logger.error(e)
  21. raise e
  22. def main() -> None:
  23. logger.info("Initializing service")
  24. init()
  25. logger.info("Service finished initializing")
  26. if __name__ == "__main__":
  27. main()