第6章 - 完整代码
🎯 本章目标
- 提供项目完整源码
- 说明如何运行项目
- 总结项目知识点
1️⃣ 项目结构
student-management/
├── app/
│ ├── __init__.py
│ ├── main.py # 主程序入口
│ ├── config.py # 配置文件
│ ├── database.py # 数据库配置
│ ├── models/
│ │ ├── __init__.py
│ │ ├── class_model.py # 班级模型
│ │ ├── student.py # 学生模型
│ │ └── score.py # 成绩模型
│ ├── schemas/
│ │ ├── __init__.py
│ │ ├── class_schema.py # 班级 Schema
│ │ ├── student.py # 学生 Schema
│ │ └── score.py # 成绩 Schema
│ ├── crud/
│ │ ├── __init__.py
│ │ ├── class_crud.py # 班级 CRUD
│ │ ├── student.py # 学生 CRUD
│ │ └── score.py # 成绩 CRUD
│ ├── api/
│ │ ├── __init__.py
│ │ ├── classes.py # 班级 API
│ │ ├── students.py # 学生 API
│ │ ├── scores.py # 成绩 API
│ │ └── statistics.py # 统计 API
│ └── utils/
│ ├── __init__.py
│ ├── response.py # 响应工具
│ ├── exceptions.py # 异常处理
│ └── logger.py # 日志工具
├── scripts/
│ └── init_data.py # 数据初始化脚本
├── requirements.txt
└── README.md
2️⃣ 完整的 main.py
"""
学生管理系统 - 主程序入口
"""
import time
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from app.config import settings
from app.database import engine, Base
from app.models import Class, Student, Score
from app.api import classes, students, scores, statistics
from app.utils.exceptions import (
http_exception_handler,
validation_exception_handler,
general_exception_handler
)
from app.utils.logger import log_info
# 创建数据库表
Base.metadata.create_all(bind=engine)
# 创建 FastAPI 应用
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
docs_url="/docs",
redoc_url="/redoc",
openapi_tags=[
{"name": "班级管理", "description": "班级的增删改查操作"},
{"name": "学生管理", "description": "学生的增删改查操作"},
{"name": "成绩管理", "description": "成绩的录入和查询"},
{"name": "数据统计", "description": "各类统计数据"},
]
)
# 配置 CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 注册异常处理器
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)
# 请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
log_info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s")
return response
# 注册路由
app.include_router(classes.router, prefix=settings.API_PREFIX, tags=["班级管理"])
app.include_router(students.router, prefix=settings.API_PREFIX, tags=["学生管理"])
app.include_router(scores.router, prefix=settings.API_PREFIX, tags=["成绩管理"])
app.include_router(statistics.router, prefix=settings.API_PREFIX, tags=["数据统计"])
@app.get("/", tags=["系统"])
def root():
"""系统首页"""
return {
"message": "欢迎使用学生管理系统",
"version": settings.PROJECT_VERSION,
"docs": "/docs",
"redoc": "/redoc"
}
@app.get("/health", tags=["系统"])
def health_check():
"""健康检查"""
return {"status": "healthy", "version": settings.PROJECT_VERSION}
3️⃣ requirements.txt
fastapi==0.104.1
uvicorn==0.24.0
sqlalchemy==2.0.23
pydantic==2.5.2
python-multipart==0.0.6
4️⃣ 运行项目
步骤 1:创建虚拟环境
# 创建项目目录
mkdir student-management
cd student-management
# 创建虚拟环境
python -m venv venv
# 激活虚拟环境
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activate
步骤 2:安装依赖
pip install -r requirements.txt
步骤 3:创建项目文件
按照项目结构创建所有文件,复制前面章节的代码。
步骤 4:运行项目
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
步骤 5:初始化测试数据
python scripts/init_data.py
步骤 6:访问 API 文档
打开浏览器访问:http://127.0.0.1:8000/docs
5️⃣ API 接口汇总
班级管理
| 方法 | 路径 | 说明 |
|---|---|---|
| POST | /api/classes | 创建班级 |
| GET | /api/classes | 获取班级列表 |
| GET | /api/classes/{id} | 获取班级详情 |
| PUT | /api/classes/{id} | 更新班级 |
| DELETE | /api/classes/{id} | 删除班级 |
学生管理
| ��法 | 路径 | 说明 |
|---|---|---|
| POST | /api/students | 创建学生 |
| GET | /api/students | 获取学生列表 |
| GET | /api/students/{id} | 获取学生详情 |
| PUT | /api/students/{id} | 更新学生 |
| DELETE | /api/students/{id} | 删除学生 |
| GET | /api/students/{id}/scores | 获取学生成绩 |
成绩管理
| 方法 | 路径 | 说明 |
|---|---|---|
| POST | /api/scores | 录入成绩 |
| POST | /api/scores/batch | 批量录入成绩 |
| GET | /api/scores | 获取成绩列表 |
| GET | /api/scores/{id} | 获取成绩详情 |
| PUT | /api/scores/{id} | 更新成绩 |
| DELETE | /api/scores/{id} | 删除成绩 |
数据统计
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | /api/statistics/overview | 总体统计 |
| GET | /api/statistics/class/{id} | 班级统计 |
| GET | /api/statistics/ranking | 成绩排名 |
| GET | /api/statistics/student/{id} | 学生成绩分析 |
6️⃣ 测试示例
创建班级
curl -X POST "http://127.0.0.1:8000/api/classes" \
-H "Content-Type: application/json" \
-d '{"name": "三年级1班", "grade": "三年级", "teacher": "刘老师"}'
创建学生
curl -X POST "http://127.0.0.1:8000/api/students" \
-H "Content-Type: application/json" \
-d '{
"student_no": "2024010",
"name": "小明",
"gender": "男",
"age": 18,
"class_id": 1
}'
录入成绩
curl -X POST "http://127.0.0.1:8000/api/scores" \
-H "Content-Type: application/json" \
-d '{
"student_id": 1,
"subject": "语文",
"score": 85.5,
"exam_date": "2024-01-15",
"exam_type": "期中考试"
}'
获取统计数据
curl "http://127.0.0.1:8000/api/statistics/overview"
获取成绩排名
curl "http://127.0.0.1:8000/api/statistics/ranking?subject=语文&limit=10"
7️⃣ 项目知识点总结
通过这个项目,你学习了:
FastAPI 基础
- ✅ 创建 FastAPI 应用
- ✅ 定义路由和接口
- ✅ 路径参数和查询参数
- ✅ 请求体处理
- ✅ 响应模型
数据验证
- ✅ Pydantic 模型定义
- ✅ 字段验证(Field)
- ✅ 枚举类型
- ✅ 嵌套模型
数据库操作
- ✅ SQLAlchemy ORM
- ✅ 数据库模型定义
- ✅ 关联关系(一对多)
- ✅ CRUD 操作
- ✅ 复杂查询
项目架构
- ✅ 分层架构(models/schemas/crud/api)
- ✅ 依赖注入
- ✅ 路由分组
- ✅ 统一响应格式
进阶功能
- ✅ 分页查询
- ✅ 条件筛选
- ✅ 数据统计
- ✅ 异常处理
- ✅ 日志记录
8️⃣ 扩展建议
如果你想继续完善这个项目,可以尝试:
- 用户认证 - 添加登录注册功能,使用 JWT 认证
- 权限控制 - 不同角色(管理员、教师、学生)有不同权限
- 文件上传 - 支持导入导出 Excel
- 前端界面 - 使用 Vue/React 开发前端
- 部署上线 - 使用 Docker 部署到服务器
- 单元测试 - 编写测试用例
- API 限流 - 防止接口被滥用
- 缓存优化 - 使用 Redis 缓存热点数据
🎉 恭喜完成!
你已经完成了整个 FastAPI 教程的学习,并且完成了一个完整的实战项目!
现在你已经具备了使用 FastAPI 开发后端 API 的能力,可以尝试开发自己的项目了!
继续学习资源
实践建议
- 多动手写代码,不要只看不练
- 遇到问题先查文档,再搜索
- 参与开源项目,学习优秀代码
- 写技术博客,总结学习心得
祝你在 FastAPI 的学习道路上越走越远!🚀
