| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- """Flask application factory for Work Statistics System."""
- import os
- from flask import Flask, send_from_directory
- from flask_sqlalchemy import SQLAlchemy
- from flask_cors import CORS
- db = SQLAlchemy()
- def create_app(config_name='default'):
- """Create and configure the Flask application.
-
- Args:
- config_name: Configuration name ('default', 'testing', 'production')
-
- Returns:
- Configured Flask application instance
- """
- # Check if static folder exists (for production with frontend build)
- static_folder = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')
- if os.path.exists(static_folder):
- app = Flask(__name__, static_folder=static_folder, static_url_path='')
- else:
- app = Flask(__name__)
-
- # Load configuration
- from app.config import config
- app.config.from_object(config[config_name])
-
- # Initialize extensions
- db.init_app(app)
- CORS(app)
-
- # Register API routes
- from app.routes import register_routes
- register_routes(app)
-
- # Serve frontend for non-API routes (SPA support)
- if app.static_folder and os.path.exists(app.static_folder):
- @app.route('/')
- def serve_index():
- return send_from_directory(app.static_folder, 'index.html')
-
- @app.errorhandler(404)
- def not_found(e):
- # Return index.html for SPA client-side routing
- return send_from_directory(app.static_folder, 'index.html')
-
- # Create database tables and initialize default admin
- with app.app_context():
- db.create_all()
- _init_default_admin()
-
- return app
- def _init_default_admin():
- """Initialize default admin account if none exists.
-
- This ensures there is always at least one admin account
- available for login when the application starts.
- """
- from flask import current_app
- from app.services.admin_service import AdminService
-
- # Skip default admin creation in testing mode
- if current_app.config.get('TESTING', False):
- return
-
- created, message = AdminService.create_default_admin()
- if created:
- print(f"[Init] {message}")
- # Silently skip if admins already exist
|