sqlalchemy FastAPI 前端实现数据库增删改查

sqlalchemy FastAPI 前端实现数据库增删改查

仅个人学习笔记,感谢点赞关注!


知识点
  • 连接数据库
  • sqlalchemy 创建表结构
  • FastAPI get post put delete操作
  • FastAPI 请求体 路径和修改参数 依赖项

代码
python 复制代码
# -*- ecoding: utf-8 -*-
# @Author: SuperLong
# @Email: miu_zxl@163.com
# @Time: 2024/9/9 17:04
import os
import uvicorn
from fastapi import FastAPI, Depends, HTTPException, Path,status
from pydantic import BaseModel
from typing import List,Optional,Set
from sqlalchemy import create_engine, Column, Integer, String, and_, select, update
from sqlalchemy.orm import sessionmaker, Mapped, DeclarativeBase, mapped_column

engine = create_engine('mysql://root:long520@localhost/test',echo=True)
class Base(DeclarativeBase):
    pass
class StudentClass(Base):
    __tablename__ = "StudentClass"

    id:Mapped[str]=mapped_column(Integer,primary_key=True)
    name:Mapped[str]=mapped_column(String(50),nullable=False)
    gender:Mapped[str]=mapped_column(String(5),nullable=False)

Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

class StudentBase(BaseModel):
    id:int
    name:str
    gender:str

class StudentIn(StudentBase):
    pass

class StudentOut(StudentBase):
    pass

def get_db():
    db = Session()
    try:
        yield db
    finally:
        db.close()

app = FastAPI()


@app.get('/students')
async def get_students(db:Session=Depends(get_db)):
    query = select(StudentClass).order_by(StudentClass.id)
    return db.execute(query).scalars().all()

@app.post('/students',response_model=StudentOut)
async def create_students(student:StudentIn,db:Session=Depends(get_db)):
    query = select(StudentClass).where(StudentClass.name == student.name)
    result = db.execute(query).scalars().all()
    if result:
        raise HTTPException(status_code=400,detail=f"学生 {student.name} 已存在")
    new_student = StudentClass(id=student.id,name=student.name,gender=student.gender)
    db.add(new_student)
    db.commit()
    return new_student

@app.put('/students/{student_id}',response_model=StudentOut)
async def update_students(*,student_id:int=Path(...),student:StudentBase,db:Session=Depends(get_db)):
    query = select(StudentClass).where(StudentClass.id == student_id)
    result = db.execute(query).scalar()
    if not result:
        raise HTTPException(status_code=400, detail=f"学生ID {student_id} 不存在")
    def update_mm(students:dict,changes:dict):
        for keys,values in changes.items():
            setattr(students,keys,values)
    update_mm(result,student.model_dump())
    db.commit()
    return result

@app.delete('/students/{student_id}',response_model=StudentOut)
def delete_students(student_id:int=Path(...),db:Session=Depends(get_db)):
    query = select(StudentClass).where(student_id == StudentClass.id)
    result = db.execute(query).scalar()
    if not result:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"学生ID {student_id} 不存在")
    db.delete(result)
    db.commit()
    return result

if __name__ == '__main__':
    print(os.path.split(os.path.abspath(__file__))[1])
    uvicorn.run(port=5025,app=f"{os.path.split(os.path.abspath(__file__))[1].split('.')[0]}:app",reload=True)


# # todo 增
# students = [
#             StudentClass(id=1, name="张",gender="男",phone_number="13463135455"),
#             StudentClass(id=2, name="张龍",gender="男",phone_number="13463125455"),
#             StudentClass(id=3, name="张晓同",gender="男",phone_number="13463145455"),
#             StudentClass(id=4, name="张晓里",gender="男",phone_number="13463165455"),
# ]
# session.add_all(students)
# session.commit()
# # todo 查
# result = session.query(StudentClass).filter(StudentClass.gender == "男").all()
# for ii in result:
#     print("name:",ii.id)
#     print("brithday:",ii.name)

# todo 改
# result = session.query(StudentClass).filter(
#     and_(
#     StudentClass.gender == "男",
#     StudentClass.name == "李楠"
#     )
# ).update(
#     {StudentClass.phone_number:"123456789"}
# )
#
# session.commit()
# todo 删
# result = session.query(StudentClass).filter(
#     and_(
#         StudentClass.gender == "男",
#         StudentClass.name == "李佳"
#     )
# ).delete()
# session.commit()

目前专注于NLP、大模型和前后端的技术学习和分享
感谢大家的关注与支持!

相关推荐
吴文周1 小时前
告别重复劳动:一套插件让 AI 替你写代码、修Bug、做测试、上生产
前端·后端·ai编程
Mh2 小时前
我决定写一个 3D 地球仪来记录下我要去的地方
前端·javascript·动效
yaoxin5211232 小时前
390. Java IO API - WatchDir 示例
java·前端·python
懒狗小前端2 小时前
做了一个 codex 的中文文档网站,做的不好可以随便喷
前端·后端
sunshine8853 小时前
财务RPA的深水区应用:超越自动化,迈向智能决策支持
数据库
efir OONA3 小时前
MySQL数据库误删恢复_mysql 数据 误删
数据库·mysql·adb
zhangchaoxies3 小时前
如何在 Go 中安全复制接口指针所指向的值
jvm·数据库·python
. . . . .3 小时前
ref、useRef 和 forwardRef
前端·javascript·react.js
曲幽3 小时前
FastAPI + Pydantic 模型终极实战手册:从能跑就行到固若金汤,这些技巧你一定用得上
python·fastapi·web·model·field·pydantic·validator·basemodel
energy_DT4 小时前
2026年海上钻井平台数字孪生平台:引领海洋能源数字化转型
前端