03. 零基础小白直接上手FastAPI开发增删改查接口
安装插件 防止数据库连接出现异常
pip install cryptography
专业接口测试工具
JSON 教程
https://www.runoob.com/json/json-tutorial.html

数据库的操作结果 必须使用 await 接收,否则没法正常获取结果
db_stu = await Student.get_or_none(no=student_model.no)
传递参数
- 路径参数:/student/delete/{stu_id} stu_id: int

- form 参数 ?no=xxx&name=xxx

- 一般新增、更新数据,需要传递 json 对象的情况
{
"id": 1,
"name": "青哥哥真帅"
}
假数据
INSERT INTO `fastapi_vue3`.`student` (`id`, `no`, `name`, `clazz`, `major`, `college`, `phone`, `email`, `address`) VALUES
(1, '20231001', '青哥哥真帅', '计科1班', '计算机科学与技术', '计算机学院', '13699885599', 'qgg@163.com', '安徽合肥'),
(2, '20231002', '张三', '计科1班', '计算机科学与技术', '计算机学院', '13800138001', 'zhangsan@163.com', '北京海淀'),
(3, '20231003', '李四', '计科2班', '计算机科学与技术', '计算机学院', '13800138002', 'lisi@163.com', '上海浦东'),
(4, '20231004', '王五', '软件1班', '软件工程', '计算机学院', '13800138003', 'wangwu@163.com', '广东深圳'),
(5, '20231005', '赵六', '软件1班', '软件工程', '计算机学院', '13800138004', 'zhaoliu@163.com', '浙江杭州'),
(6, '20231006', '钱七', '网络1班', '网络工程', '计算机学院', '13800138005', 'qianqi@163.com', '江苏南京'),
(7, '20231007', '孙八', '网络1班', '网络工程', '计算机学院', '13800138006', 'sunba@163.com', '四川成都'),
(8, '20231008', '周九', '数据1班', '数据科学', '计算机学院', '13800138007', 'zhoujiu@163.com', '湖北武汉'),
(9, '20231009', '吴十', '数据1班', '数据科学', '计算机学院', '13800138008', 'wushi@163.com', '陕西西安'),
(10, '20231010', '郑十一', '计科3班', '计算机科学与技术', '计算机学院', '13800138009', 'zhengshiyi@163.com', '重庆渝中'),
(11, '20231011', '王小明', '软件2班', '软件工程', '计算机学院', '13800138010', 'wangxiaoming@163.com', '湖南长沙'),
(12, '20231012', '李晓红', '计科1班', '计算机科学与技术', '计算机学院', '13800138011', 'lixiaohong@163.com', '山东济南'),
(13, '20231013', '张伟', '网络2班', '网络工程', '计算机学院', '13800138012', 'zhangwei@163.com', '福建厦门'),
(14, '20231014', '刘芳', '软件3班', '软件工程', '计算机学院', '13800138013', 'liufang@163.com', '辽宁沈阳'),
(15, '20231015', '陈明', '数据2班', '数据科学', '计算机学院', '13800138014', 'chenming@163.com', '河南郑州'),
(16, '20231016', '杨帆', '计科2班', '计算机科学与技术', '计算机学院', '13800138015', 'yangfan@163.com', '安徽芜湖'),
(17, '20231017', '黄蓉', '软件1班', '软件工程', '计算机学院', '13800138016', 'huangrong@163.com', '江西南昌'),
(18, '20231018', '周杰', '网络1班', '网络工程', '计算机学院', '13800138017', 'zhoujie@163.com', '云南昆明'),
(19, '20231019', '吴刚', '数据1班', '数据科学', '计算机学院', '13800138018', 'wugang@163.com', '广西南宁'),
(20, '20231020', '郑爽', '计科3班', '计算机科学与技术', '计算机学院', '13800138019', 'zhengshuang@163.com', '贵州贵阳'),
(21, '20231021', '王磊', '软件2班', '软件工程', '计算机学院', '13800138020', 'wanglei@163.com', '山西太原');
本节课完整的代码
import uvicorn
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from settings import TORTOISE_ORM
from routers import student
app = FastAPI()
app.include_router(student.router)
# 注册 orm
register_tortoise(app, config=TORTOISE_ORM, add_exception_handlers=True)
if __name__ == "__main__":
uvicorn.run("main:app", reload=True, port=9090)
routers/student.py
from typing import Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from models import Student
router = APIRouter(prefix="/student")
# 接收数据的模型
class StudentModel(BaseModel):
id: Optional[int] = None
no: str | None = None
name: str | None = None
clazz: str | None = None
major: str | None = None
college: str | None = None
phone: str | None = None
email: str | None = None
address: str | None = None
@router.get("/selectAll")
async def select_all(name: str = '', no: str = ''):
stu_list = await Student.filter(name__contains=name).filter(no__contains=no)
return stu_list
@router.get("/selectPage")
async def select_all(name: str = '', no: str = '', pageNum: int = 1, pageSize: int = 10):
# 数据库的总共条数 total # 当前查询页的数据 list
query = Student.filter(name__contains=name).filter(no__contains=no).order_by("-id")
stu_list = await query.offset((pageNum - 1) * pageSize).limit(pageSize)
total = await query.count()
return {"list": stu_list, "total": total}
@router.post("/add")
async def add_student(student_model: StudentModel):
if student_model.no is None:
raise HTTPException(status_code=400, detail="参数错误")
# 根据学号查询
db_stu = await Student.get_or_none(no=student_model.no)
if db_stu is None:
# 参数模型转换成 字典数据
stu_dict = student_model.model_dump(exclude={"id"}, exclude_unset=True)
# **{"no": "123"} => no=123
resp = await Student.create(**stu_dict)
return resp
else:
return None
@router.put("/update")
async def update_student(student_model: StudentModel):
if student_model.id is None:
raise HTTPException(status_code=400, detail="ID参数为空")
# 参数模型转换成 字典数据
stu_dict = student_model.model_dump(exclude={"id"}, exclude_unset=True)
resp = await Student.filter(id=student_model.id).update(**stu_dict) # update student set name = '青哥哥真帅' where id = 1
return resp
@router.delete("/delete/{stu_id}")
async def delete_student(stu_id: int):
resp = await Student.filter(id=stu_id).delete()
return resp
# 导出 router
__all__ = ["router"]