diff --git a/app/__init__.py b/app/__init__.py index 25ddae2..3fec361 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -6,6 +6,13 @@ from config import Config db = SQLAlchemy() login_manager = LoginManager() +def ensure_database(): + """Initialize database tables if they don't exist""" + try: + db.create_all() + except Exception as e: + print(f"Database initialization error: {e}") + def create_app(): app = Flask(__name__) app.config.from_object(Config) @@ -24,8 +31,4 @@ def create_app(): from app.routes import bp as main_bp app.register_blueprint(main_bp) - # Initialize database tables - with app.app_context(): - db.create_all() - return app diff --git a/app/routes.py b/app/routes.py index fe7ca91..42c86af 100644 --- a/app/routes.py +++ b/app/routes.py @@ -11,9 +11,23 @@ from app.models import User, Incident bp = Blueprint('main', __name__) +# Lazy database initialization +_db_initialized = False + +def init_db_if_needed(): + global _db_initialized + if not _db_initialized: + try: + from app import ensure_database + ensure_database() + _db_initialized = True + except Exception as e: + print(f"Database initialization failed: {e}") + @bp.route('/health') def health_check(): """Health check endpoint voor Kubernetes""" + init_db_if_needed() try: # Check database connectivity db.session.execute('SELECT 1') @@ -33,6 +47,7 @@ def health_check(): @bp.route('/') def index(): """Homepage met incident invoer""" + init_db_if_needed() return render_template('index.html') @bp.route('/add-incident', methods=['GET', 'POST'])