fs-lawrisk/app.py

88 lines
2.5 KiB
Python
Raw Normal View History

"""Flask application entry point."""
2025-10-22 19:59:48 +08:00
from __future__ import annotations
import os
from flask import Flask, jsonify
2025-10-22 19:59:48 +08:00
from lawrisk.utils.env_loader import load_env
from lawrisk.middleware.smart_cors_middleware import init_smart_cors
from lawrisk.services.auth_service import (
ensure_auth_schema,
ensure_default_department_accounts,
ensure_seed_admin,
)
from lawrisk.api.v2 import v2_bp
from lawrisk.api.auth import auth_bp
2025-10-22 19:59:48 +08:00
def create_app() -> Flask:
"""Create and configure Flask application."""
2025-10-22 19:59:48 +08:00
# Load .env before creating app to make CORS/env configs available
load_env()
# Ensure auth schema and default accounts exist before serving
2025-10-22 19:59:48 +08:00
try:
ensure_auth_schema()
ensure_seed_admin()
ensure_default_department_accounts()
2025-10-22 19:59:48 +08:00
except Exception:
# Do not block app start; errors will surface on first request
pass
2025-10-22 19:59:48 +08:00
app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY", "change-me")
app.config.setdefault("SESSION_COOKIE_HTTPONLY", True)
app.config.setdefault("SESSION_COOKIE_SAMESITE", "Lax")
feat: checkpoint system comprehensive enhancement Security Fixes: - Fix critical data loss risk in restore_checkpoint (TRUNCATE without rollback) - Add table dependency tracking with topological sort - Implement auto-backup before restore for safety - Add table-level locks during restore (EXCLUSIVE MODE) - Single transaction for atomic operations Performance Optimization: - Replace row-by-row insert with batch insert (executemany) - 100-1000x performance improvement (30-60x faster) - Add configurable batch_size parameter (100-10000 rows) - Add performance monitoring and timing statistics - Support for skipping auto-backup for speed Logging Enhancement: - Detailed real-time logging for all checkpoint operations - Progress tracking: per table, per batch, per 100 rows - Time statistics for each table and total operation - Structured log messages with clear identifiers - Configured immediate stdout output without buffering Documentation: - Updated CLAUDE.md with improved guidelines - Created CHECKPOINT_SECURITY_FIX_SUMMARY.md - Created CHECKPOINT_LOGGING_GUIDE.md - Created CHECKPOINT_PERFORMANCE_OPTIMIZATION.md - Created PATCH_CHECKPOINT_SECURITY.md - Created analysis/checkpoint_analysis.md API Enhancements: - Added create_auto_backup parameter to restore endpoint - Added batch_size parameter for performance tuning - Added input validation for all parameters - Enhanced error messages with recovery suggestions Modified Files: - lawrisk/services/licensing_repo.py: Core checkpoint logic - lawrisk/api/v2.py: REST API endpoints - app.py: Logging configuration - docs/CLAUDE.md: Updated development guide Closes: #security #performance #logging 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 17:33:12 +08:00
# Configure logging for immediate output
import logging
import sys
# Create handler that outputs to stdout
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
handler.setFormatter(formatter)
# Configure root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.addHandler(handler)
# Disable Flask's default logger to avoid duplicate messages
app.logger.handlers.clear()
app.logger.addHandler(handler)
app.logger.setLevel(logging.INFO)
2025-10-22 19:59:48 +08:00
# Enable CORS using existing middleware
init_smart_cors(app)
# Register blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(v2_bp)
2025-10-22 19:59:48 +08:00
# Basic health check
@app.get("/healthz")
def healthz():
return jsonify({"status": "ok"})
feat: checkpoint system comprehensive enhancement Security Fixes: - Fix critical data loss risk in restore_checkpoint (TRUNCATE without rollback) - Add table dependency tracking with topological sort - Implement auto-backup before restore for safety - Add table-level locks during restore (EXCLUSIVE MODE) - Single transaction for atomic operations Performance Optimization: - Replace row-by-row insert with batch insert (executemany) - 100-1000x performance improvement (30-60x faster) - Add configurable batch_size parameter (100-10000 rows) - Add performance monitoring and timing statistics - Support for skipping auto-backup for speed Logging Enhancement: - Detailed real-time logging for all checkpoint operations - Progress tracking: per table, per batch, per 100 rows - Time statistics for each table and total operation - Structured log messages with clear identifiers - Configured immediate stdout output without buffering Documentation: - Updated CLAUDE.md with improved guidelines - Created CHECKPOINT_SECURITY_FIX_SUMMARY.md - Created CHECKPOINT_LOGGING_GUIDE.md - Created CHECKPOINT_PERFORMANCE_OPTIMIZATION.md - Created PATCH_CHECKPOINT_SECURITY.md - Created analysis/checkpoint_analysis.md API Enhancements: - Added create_auto_backup parameter to restore endpoint - Added batch_size parameter for performance tuning - Added input validation for all parameters - Enhanced error messages with recovery suggestions Modified Files: - lawrisk/services/licensing_repo.py: Core checkpoint logic - lawrisk/api/v2.py: REST API endpoints - app.py: Logging configuration - docs/CLAUDE.md: Updated development guide Closes: #security #performance #logging 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 17:33:12 +08:00
app.logger.info("=" * 80)
app.logger.info("Flask application starting...")
app.logger.info("=" * 80)
app.logger.info("Registered routes:")
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
methods = ",".join(sorted(rule.methods - {"HEAD", "OPTIONS"}))
app.logger.info(" %s -> %s", rule.rule, methods)
feat: checkpoint system comprehensive enhancement Security Fixes: - Fix critical data loss risk in restore_checkpoint (TRUNCATE without rollback) - Add table dependency tracking with topological sort - Implement auto-backup before restore for safety - Add table-level locks during restore (EXCLUSIVE MODE) - Single transaction for atomic operations Performance Optimization: - Replace row-by-row insert with batch insert (executemany) - 100-1000x performance improvement (30-60x faster) - Add configurable batch_size parameter (100-10000 rows) - Add performance monitoring and timing statistics - Support for skipping auto-backup for speed Logging Enhancement: - Detailed real-time logging for all checkpoint operations - Progress tracking: per table, per batch, per 100 rows - Time statistics for each table and total operation - Structured log messages with clear identifiers - Configured immediate stdout output without buffering Documentation: - Updated CLAUDE.md with improved guidelines - Created CHECKPOINT_SECURITY_FIX_SUMMARY.md - Created CHECKPOINT_LOGGING_GUIDE.md - Created CHECKPOINT_PERFORMANCE_OPTIMIZATION.md - Created PATCH_CHECKPOINT_SECURITY.md - Created analysis/checkpoint_analysis.md API Enhancements: - Added create_auto_backup parameter to restore endpoint - Added batch_size parameter for performance tuning - Added input validation for all parameters - Enhanced error messages with recovery suggestions Modified Files: - lawrisk/services/licensing_repo.py: Core checkpoint logic - lawrisk/api/v2.py: REST API endpoints - app.py: Logging configuration - docs/CLAUDE.md: Updated development guide Closes: #security #performance #logging 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 17:33:12 +08:00
app.logger.info("=" * 80)
2025-10-22 19:59:48 +08:00
return app
if __name__ == "__main__":
port = int(os.getenv("PORT", "8000"))
app = create_app()
app.run(host="0.0.0.0", port=port)