78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
# main.py
|
|
# 项目入口文件:创建 FastAPI 应用、注册路由、建表、挂载前端页面
|
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import RedirectResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from config import settings
|
|
from database import engine, Base
|
|
# 导入 model 包触发全部模型注册到 Base.metadata
|
|
import model # noqa: F401
|
|
|
|
from api import auth
|
|
from api import classes as classes_api
|
|
from api import teachers as teachers_api
|
|
from api import students as students_api
|
|
from api import scores as scores_api
|
|
from api import employment as employment_api
|
|
from api import statistics as statistics_api
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""应用生命周期:启动时自动建表(不使用 Alembic,开发/演示环境够用)"""
|
|
Base.metadata.create_all(bind=engine)
|
|
yield
|
|
|
|
|
|
# 1. 创建 FastAPI 实例
|
|
app = FastAPI(
|
|
title=settings.APP_NAME,
|
|
description="基于 FastAPI + SQLAlchemy 的学生管理系统:学生信息、考核成绩、就业管理、班级/老师管理、统计分析",
|
|
version=settings.APP_VERSION,
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# 2. 添加跨域中间件(生产环境应指定具体域名)
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 3. 注册子路由
|
|
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
|
|
app.include_router(classes_api.router, prefix="/api/classes", tags=["班级管理"])
|
|
app.include_router(teachers_api.router, prefix="/api/teachers", tags=["老师管理"])
|
|
app.include_router(students_api.router, prefix="/api/students", tags=["学生管理"])
|
|
app.include_router(scores_api.router, prefix="/api/scores", tags=["成绩管理"])
|
|
app.include_router(employment_api.router, prefix="/api/employment", tags=["就业管理"])
|
|
app.include_router(statistics_api.router, prefix="/api/statistics", tags=["统计分析"])
|
|
|
|
# 4. 挂载前端静态页面
|
|
app.mount("/static", StaticFiles(directory="static", html=True), name="static")
|
|
|
|
|
|
@app.get("/", include_in_schema=False)
|
|
async def root():
|
|
"""根路径重定向到前端管理页面"""
|
|
return RedirectResponse(url="/static/index.html")
|
|
|
|
|
|
# 5. 直接运行时启动 uvicorn
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(
|
|
"main:app",
|
|
host="0.0.0.0",
|
|
port=8000,
|
|
reload=settings.DEBUG,
|
|
)
|