Files
PWF/Application/web.py

93 lines
2.7 KiB
Python
Raw Normal View History

2025-11-05 16:21:05 +08:00
from fastapi import FastAPI
import asyncio
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from ..CoreModules.middleware import ConcurrencyLimitMiddleware
from ..CoreModules.plugin_interface import ImportPlugins
2025-11-08 01:24:50 +08:00
from ..CoreModules.clock_scheduler import get_clock_scheduler
2025-11-05 23:23:42 +08:00
from ..CoreRouters import callback, health
2025-11-05 16:21:05 +08:00
from ..Convention.Runtime.GlobalConfig import *
from ..Convention.Runtime.Architecture import Architecture
2025-11-07 23:47:33 +08:00
logger: ProjectConfig = Architecture.Get(ProjectConfig)
2025-11-06 10:55:39 +08:00
APP_CONFIG = {
"docs_url": "/docs",
}
2025-11-05 16:21:05 +08:00
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
2025-11-08 01:24:50 +08:00
scheduler = get_clock_scheduler()
await scheduler.start()
2025-11-05 16:21:05 +08:00
# 启动
2025-11-07 23:47:33 +08:00
logger.Log("Info", "应用启动中...")
2025-11-05 16:21:05 +08:00
# 初始化数据
2025-11-07 23:47:33 +08:00
logger.Log("Info", "初始化数据...")
2025-11-05 16:21:05 +08:00
# 启动后台清理
2025-11-07 23:47:33 +08:00
logger.Log("Info", "启动后台清理...")
2025-11-05 16:21:05 +08:00
try:
2025-11-08 01:24:50 +08:00
yield
2025-11-05 16:21:05 +08:00
finally:
2025-11-08 01:24:50 +08:00
# 关闭
try:
logger.Log("Info", "关闭应用...")
await scheduler.stop()
except asyncio.CancelledError:
pass
finally:
logger.Log("Info", "关闭应用完成...")
2025-11-05 16:21:05 +08:00
2025-11-06 10:55:39 +08:00
def generate_app(kwargs: dict) -> FastAPI:
2025-11-05 16:21:05 +08:00
'''
生成FastAPI应用
'''
2025-11-07 23:47:33 +08:00
config: ProjectConfig = Architecture.Get(ProjectConfig)
2025-11-06 10:55:39 +08:00
kwargs.update(**APP_CONFIG)
app = FastAPI(**kwargs, lifespan=lifespan)
2025-11-05 16:21:05 +08:00
# 添加并发限制中间件
app.add_middleware(ConcurrencyLimitMiddleware)
# 注册路由
app.include_router(callback.router, prefix="/api", tags=["callback"])
app.include_router(health.router, tags=["health"])
2025-11-06 10:55:39 +08:00
ImportPlugins(app, config.FindItem("plugin_dir", "Plugins"))
2025-11-05 16:21:05 +08:00
# 注册至框架中
Architecture.Register(FastAPI, app, lambda: None)
config.SaveProperties()
return app
2025-11-07 23:47:33 +08:00
app: FastAPI = generate_app(logger.FindItem("app_config", {}))
2025-11-05 16:21:05 +08:00
@app.get("/")
async def root():
"""根路径"""
2025-11-07 23:47:33 +08:00
config: ProjectConfig = Architecture.Get(ProjectConfig)
2025-11-06 10:55:39 +08:00
app_name = config.FindItem("app_name", "Application")
app_version = config.FindItem("app_version", "0.0.0")
config.SaveProperties()
2025-11-05 16:21:05 +08:00
return JSONResponse({
2025-11-06 10:55:39 +08:00
"message": app_name,
"version": app_version,
2025-11-05 16:21:05 +08:00
"status": "running"
})
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
"""全局异常处理"""
2025-11-07 23:47:33 +08:00
logger.Log("Error", f"未捕获的异常: {exc}\n{format_traceback_info()}")
2025-11-05 16:21:05 +08:00
return JSONResponse(
status_code=500,
content={"error": "Internal Server Error", "detail": str(exc)}
)
2025-11-07 23:47:33 +08:00
logger.SaveProperties()
2025-11-05 16:21:05 +08:00
# 除了从本模块导出的app使用API实例外, 还可以从Architecture.Get(FastAPI)获取
__all__ = ["app"]