import os import logging from flask import Flask from flask_cors import CORS # 修改相对导入为绝对导入 import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from config import active_config def setup_logging(app): """设置日志""" log_level = getattr(logging, active_config.LOG_LEVEL.upper(), logging.INFO) # 确保日志目录存在 log_dir = os.path.dirname(active_config.LOG_FILE) if not os.path.exists(log_dir): os.makedirs(log_dir) # 配置日志 logging.basicConfig( level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler(active_config.LOG_FILE), logging.StreamHandler() ] ) app.logger.setLevel(log_level) return app def create_app(config=None): """创建并配置Flask应用""" app = Flask(__name__) # 加载配置 app.config.from_object(active_config) # 如果提供了自定义配置,加载它 if config: app.config.from_object(config) # 允许跨域请求 CORS(app) # 设置日志 app = setup_logging(app) # 确保存储邮件的目录存在 os.makedirs(active_config.MAIL_STORAGE_PATH, exist_ok=True) # 初始化数据库 from .models import init_db init_db() # 注册蓝图 from .api import api_bp app.register_blueprint(api_bp) # 首页路由 @app.route("/") def index(): return { "name": "Email System", "version": "1.0.0", "status": "running" } app.logger.info('应用初始化完成') return app