mirror of
https://github.com/Jerryplusy/AI-powered-switches.git
synced 2025-07-04 05:09:19 +00:00
49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
from fastapi import FastAPI, responses
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from starlette.middleware import Middleware # 新增导入
|
||
from src.backend.app.api.endpoints import router
|
||
from src.backend.app.utils.logger import setup_logging
|
||
from src.backend.config import settings
|
||
from .services.switch_traffic_monitor import get_switch_monitor
|
||
from .services.traffic_monitor import traffic_monitor
|
||
from src.backend.app.api.database import init_db
|
||
|
||
def create_app() -> FastAPI:
|
||
# 初始化数据库
|
||
init_db()
|
||
|
||
# 启动流量监控
|
||
traffic_monitor.start_monitoring()
|
||
|
||
# 设置日志
|
||
setup_logging()
|
||
|
||
# 创建FastAPI应用(使用新的中间件配置方式)
|
||
app = FastAPI(
|
||
title=settings.APP_NAME,
|
||
debug=settings.DEBUG,
|
||
docs_url=f"{settings.API_PREFIX}/docs",
|
||
redoc_url=f"{settings.API_PREFIX}/redoc",
|
||
openapi_url=f"{settings.API_PREFIX}/openapi.json",
|
||
middleware=[ # 这里直接配置中间件
|
||
Middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
]
|
||
)
|
||
|
||
# 添加根路径重定向
|
||
@app.get("/", include_in_schema=False)
|
||
async def root():
|
||
return responses.RedirectResponse(url=f"{settings.API_PREFIX}/docs")
|
||
|
||
# 添加API路由
|
||
app.include_router(router, prefix=settings.API_PREFIX)
|
||
|
||
return app
|
||
|
||
app = create_app() |