__init__.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """Flask application factory for Work Statistics System."""
  2. import os
  3. from flask import Flask, send_from_directory
  4. from flask_sqlalchemy import SQLAlchemy
  5. from flask_cors import CORS
  6. db = SQLAlchemy()
  7. def create_app(config_name='default'):
  8. """Create and configure the Flask application.
  9. Args:
  10. config_name: Configuration name ('default', 'testing', 'production')
  11. Returns:
  12. Configured Flask application instance
  13. """
  14. # Check if static folder exists (for production with frontend build)
  15. static_folder = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')
  16. if os.path.exists(static_folder):
  17. app = Flask(__name__, static_folder=static_folder, static_url_path='')
  18. else:
  19. app = Flask(__name__)
  20. # Load configuration
  21. from app.config import config
  22. app.config.from_object(config[config_name])
  23. # Initialize extensions
  24. db.init_app(app)
  25. CORS(app)
  26. # Register API routes
  27. from app.routes import register_routes
  28. register_routes(app)
  29. # Serve frontend for non-API routes (SPA support)
  30. if app.static_folder and os.path.exists(app.static_folder):
  31. @app.route('/')
  32. def serve_index():
  33. return send_from_directory(app.static_folder, 'index.html')
  34. @app.errorhandler(404)
  35. def not_found(e):
  36. # Return index.html for SPA client-side routing
  37. return send_from_directory(app.static_folder, 'index.html')
  38. # Create database tables and initialize default admin
  39. with app.app_context():
  40. db.create_all()
  41. _init_default_admin()
  42. return app
  43. def _init_default_admin():
  44. """Initialize default admin account if none exists.
  45. This ensures there is always at least one admin account
  46. available for login when the application starts.
  47. """
  48. from flask import current_app
  49. from app.services.admin_service import AdminService
  50. # Skip default admin creation in testing mode
  51. if current_app.config.get('TESTING', False):
  52. return
  53. created, message = AdminService.create_default_admin()
  54. if created:
  55. print(f"[Init] {message}")
  56. # Silently skip if admins already exist