diff --git a/api/app.py b/api/app.py index c4c08bd..5374030 100644 --- a/api/app.py +++ b/api/app.py @@ -4,10 +4,29 @@ from flask_jwt_extended import JWTManager from jwt import ExpiredSignatureError from models import db, RevokedToken import os +from sqlalchemy import text +from sqlalchemy.exc import DatabaseError +import time from utils import init_db from views import user_bp from werkzeug.exceptions import HTTPException +MAX_RETRIES = 100 + +def wait_for_db(): + for retries in range(MAX_RETRIES): + try: + with db.engine.connect() as connection: + connection.execute(text("SELECT 1")) + print("Successfully connected with database.") + return + except DatabaseError: + print(f"Waiting for database... (retry {retries + 1})") + time.sleep(3) + print("Failed to connect to database.") + raise Exception("Database not ready after multiple retries.") + + def create_app(config_name="default"): """Creates and returns a new instance of Flask app.""" load_dotenv() @@ -53,6 +72,7 @@ def create_app(config_name="default"): # Fill database by initial values (only if we are not testing) with app.app_context(): + wait_for_db() db.create_all() if config_name != "testing": init_db()