81 lines
3.2 KiB
Python
81 lines
3.2 KiB
Python
# main.py
|
||
# 项目入口文件:创建 FastAPI 应用、注册路由
|
||
|
||
from pathlib import Path
|
||
|
||
from fastapi import FastAPI, Request
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
from api import statistics_api, stu_score_api, cls_mgmt_api, employ_api, stu_api, teacher_api, advisor_api
|
||
from dao.exceptions import DaoError
|
||
|
||
# 1. 创建 FastAPI 实例
|
||
app = FastAPI(
|
||
title="码力全开: 学生管理系统",
|
||
description="本项目旨在开发一个基于 FastAPI 的学生管理系统,"
|
||
"提供学生基本信息管理、考核成绩管理、就业管理、教师/顾问管理和统计分析等核心功能模块。"
|
||
"系统采用 RESTful API 设计,支持前后端分离架构。<br>",
|
||
version="0.1.0"
|
||
)
|
||
|
||
# 2. 添加跨域中间件(允许前端跨域请求)
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"], # 允许所有来源,生产环境应指定具体域名
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 3. 注册 DAO 层异常处理器
|
||
# dao 层只抛 NotFoundError / ConflictError 这类业务异常,不依赖 FastAPI;
|
||
# 在这里统一映射成 HTTP 状态码(404 / 409),接口层因此不需要写 try/except。
|
||
@app.exception_handler(DaoError)
|
||
async def dao_error_handler(request: Request, exc: DaoError):
|
||
"""把 DAO 层异常转成 {"detail": "..."} 的标准错误响应。"""
|
||
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
||
|
||
|
||
# 4. 注册子路由
|
||
app.include_router(statistics_api.router, prefix="/api/stats", tags=["统计分析模块(动态查询与综合能力锻炼)"])
|
||
|
||
app.include_router(stu_score_api.router, prefix="/api/score", tags=["学生成绩管理模块"])
|
||
|
||
app.include_router(cls_mgmt_api.router, prefix="/api/classes", tags=["班级管理模块"])
|
||
|
||
app.include_router(employ_api.router, prefix="/api/employ", tags=["学生就业管理模块"])
|
||
|
||
app.include_router(teacher_api.router, prefix="/api/teacher", tags=["教师信息管理模块"])
|
||
|
||
app.include_router(advisor_api.router, prefix="/api/advisor", tags=["顾问信息管理模块"])
|
||
|
||
app.include_router(stu_api.router, prefix="/api/student", tags=["学生信息管理模块"])
|
||
|
||
|
||
# 5. 挂载前端静态页面(原生 HTML/CSS/JS 单页应用,无需构建)
|
||
# 访问 http://localhost:8002/ui 即可打开可视化管理界面
|
||
STATIC_DIR = Path(__file__).resolve().parent / "static"
|
||
if STATIC_DIR.is_dir():
|
||
app.mount("/ui", StaticFiles(directory=str(STATIC_DIR), html=True), name="ui")
|
||
|
||
|
||
# 6. 根路径
|
||
@app.get("/")
|
||
async def root():
|
||
return {"message": "欢迎访问 码力全开: 学生管理系统 分层示例!请访问 /docs 查看 API 文档。"}
|
||
|
||
|
||
# 7. 如果直接运行此文件,启动 uvicorn 服务器
|
||
if __name__ == "__main__":
|
||
import os
|
||
|
||
import uvicorn
|
||
uvicorn.run(
|
||
"main:app", # 指定应用位置(模块名:应用变量名)
|
||
host=os.getenv("HOST", "0.0.0.0"), # 0.0.0.0 才能在容器内被外部访问
|
||
port=int(os.getenv("PORT", "8002")), # 端口(避开原项目的 8001)
|
||
reload=os.getenv("APP_RELOAD", "false").lower() == "true" # 开发模式可设为 true
|
||
)
|