implement lazy database initialization and ensure database setup in routes
All checks were successful
Build and Push Image / build-and-push (push) Successful in 15s

This commit is contained in:
Michael Trip 2026-01-09 22:29:28 +01:00
parent 995cadeb27
commit ae0556468f
2 changed files with 22 additions and 4 deletions

View file

@ -6,6 +6,13 @@ from config import Config
db = SQLAlchemy() db = SQLAlchemy()
login_manager = LoginManager() 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(): def create_app():
app = Flask(__name__) app = Flask(__name__)
app.config.from_object(Config) app.config.from_object(Config)
@ -24,8 +31,4 @@ def create_app():
from app.routes import bp as main_bp from app.routes import bp as main_bp
app.register_blueprint(main_bp) app.register_blueprint(main_bp)
# Initialize database tables
with app.app_context():
db.create_all()
return app return app

View file

@ -11,9 +11,23 @@ from app.models import User, Incident
bp = Blueprint('main', __name__) 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') @bp.route('/health')
def health_check(): def health_check():
"""Health check endpoint voor Kubernetes""" """Health check endpoint voor Kubernetes"""
init_db_if_needed()
try: try:
# Check database connectivity # Check database connectivity
db.session.execute('SELECT 1') db.session.execute('SELECT 1')
@ -33,6 +47,7 @@ def health_check():
@bp.route('/') @bp.route('/')
def index(): def index():
"""Homepage met incident invoer""" """Homepage met incident invoer"""
init_db_if_needed()
return render_template('index.html') return render_template('index.html')
@bp.route('/add-incident', methods=['GET', 'POST']) @bp.route('/add-incident', methods=['GET', 'POST'])