76 lines
2.0 KiB
Python

# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt
"""
Jingrow 应用入口
"""
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from jingrow.utils.router_auto_register import include_routers_from_package
from jingrow.services.scheduler import start_scheduler, stop_scheduler
from jingrow.services.whitelist import router
from jingrow.services.scheduler import get_scheduler_status
from jingrow.core.hooks.init_hooks import init_hooks
logger = logging.getLogger("uvicorn.error")
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
# 启动事件
try:
# 初始化钩子系统
init_hooks()
logger.info("钩子系统已初始化")
# 启动调度器
await start_scheduler()
logger.info("调度器已启动")
# 验证调度器状态
status = get_scheduler_status()
logger.info(f"调度器状态: 运行={status['running']}, 任务数={status['total_jobs']}")
except Exception as e:
logger.exception(f"启动调度器失败: {e}")
yield
# 关闭事件
try:
await stop_scheduler()
logger.info("调度器已停止")
except Exception as e:
logger.exception(f"停止调度器失败: {e}")
def create_app():
"""创建FastAPI应用"""
app = FastAPI(
title="Jingrow",
description="Jingrow Backend",
version="1.0.0",
lifespan=lifespan
)
# 添加CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 自动注册 Jingrow 框架的静态路由(无前缀)
include_routers_from_package(app, "jingrow.api")
# 手动注册动态路由(最后注册,避免冲突)
app.include_router(router)
return app
app = create_app()