78 lines
2.1 KiB
Python
78 lines
2.1 KiB
Python
# main0814.py
|
||
# 项目入口文件:创建 FastAPI 应用、注册路由、创建数据库表
|
||
from fastapi import FastAPI
|
||
from starlette.middleware.cors import CORSMiddleware
|
||
|
||
from api import student_api, advisor_api, employment_api, score_api, class_api, teacher_api
|
||
from init_db import init_all, drop_tables
|
||
|
||
# 2. 创建 FastAPI 实例
|
||
app = FastAPI(
|
||
title="FastAPI + SQLAlchemy 分层架构(MySQL)",
|
||
description="用户管理示例,演示分层架构和 MySQL 集成",
|
||
version="1.0.0"
|
||
)
|
||
|
||
# 3. 添加跨域中间件(允许前端跨域请求)
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"], # 允许所有来源,生产环境应指定具体域名
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 4. 注册子路由
|
||
# prefix 为路由前缀,所有用户接口都以 /api/users 开头
|
||
app.include_router(
|
||
student_api.router,
|
||
prefix="/api/studentsManagement",
|
||
tags=["学生管理 (文涛,浩霖)"]
|
||
)
|
||
#
|
||
app.include_router(
|
||
class_api.router,
|
||
prefix="/api/studentsManagement",
|
||
tags=["班级管理 (薛炎)"]
|
||
)
|
||
#
|
||
app.include_router(
|
||
teacher_api.router,
|
||
prefix="/api/studentsManagement",
|
||
tags=["老师管理 (广龙)"]
|
||
)
|
||
#
|
||
app.include_router(
|
||
advisor_api.router,
|
||
prefix="/api/studentsManagement",
|
||
tags=["顾问管理 (子镜)"]
|
||
)
|
||
#
|
||
app.include_router(
|
||
score_api.router,
|
||
prefix="/api/studentsManagement",
|
||
tags=["成绩管理 (广湘)"]
|
||
)
|
||
|
||
app.include_router(
|
||
employment_api.router,
|
||
prefix="/api/studentsManagement",
|
||
tags=["就业管理 (周兴)"]
|
||
)
|
||
|
||
# 5. 根路径
|
||
@app.get("/")
|
||
async def root():
|
||
return {"message": "欢迎访问 FastAPI + SQLAlchemy 分层示例!请访问 /docs 查看 API 文档。"}
|
||
|
||
# 6. 如果直接运行此文件,启动 uvicorn 服务器
|
||
if __name__ == "__main__":
|
||
# drop_tables()
|
||
init_all(True, False)
|
||
import uvicorn
|
||
uvicorn.run(
|
||
"main:app", # 指定应用位置(模块名:应用变量名)
|
||
host="localhost", # 监听所有网络接口
|
||
port=8004, # 端口
|
||
reload=True # 开发模式,代码变动自动重启
|
||
) |