方向不对,努力白费,经验类测试技术才是职场重要保险! | (点击→)【提醒】AI赋能的前提是对常规测试技术非常的熟悉,联系作者vx了解

FastAPI系列(20):ORM添加表记录

 

本系列汇总,请查看这里https://www.cnblogs.com/uncleyong/p/19503695

请求数据:符合要求

main.py

import uvicorn
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise

from test_orm.api.student import student_api
from test_orm.settings import TORTOISE_ORM

app = FastAPI()

app.include_router(student_api, prefix="/student", tags=["学生接口"])

# register_tortoise是注册函数,fastapi一旦运行,register_tortoise已经执行,通过传递进去的app对象,监听服务启动和终止事件
register_tortoise(
    app=app,
    config=TORTOISE_ORM,
)

if __name__ == '__main__':
    uvicorn.run('main:app', host='127.0.0.1', port=8001, reload=True, workers=1)

 

api目录下student.py

from typing import List

from fastapi import APIRouter
from pydantic import BaseModel, field_validator

from test_orm.models import Student

student_api = APIRouter()


class StudentIn(BaseModel):
    name: str
    pwd: str
    sno: int
    clas_id: int
    courses: List[int] = []

    @field_validator("name")
    def name_must_alpha(cls, value):  # 使用 cls 而不是 self
        assert value.isalpha(), 'name must be alpha'
        return value

    @field_validator("sno")
    @classmethod  # 必须在下面
    def sno_validate(cls, value):
        assert 1000 <= value < 10000, '学号要在[1000-10000)的范围内'
        return value


@student_api.post("/")
async def addStudent(student_in: StudentIn):
    # 方式1
    student = Student(name=student_in.name, pwd=student_in.pwd, sno=student_in.sno, clas_id=student_in.clas_id)
    await student.save()  # 插入到数据库student表;必须要加await
    print(student, type(student))
    return student

 

接口文档

image

 

请求数据

image

 

响应结果

image

 

image

 

数据库新增id为3的数据

image

 

查询添加的数据

下面直接返回,也可以对响应内容做要求

from typing import List

from fastapi import APIRouter
from pydantic import BaseModel, field_validator

from test_orm.models import Student, Course

student_api = APIRouter()


@student_api.get("/{student_id}")
async def getOneStudent(student_id: int):
    student = await Student.get(id=student_id)

    return student

  

响应结果

image

 

请求数据:不符合要求

image

 

响应结果

image

 

方法2更简洁,没有save

@student_api.post("/")
async def addStudent(student_in: StudentIn):
    # 方式1
    # student = Student(name=student_in.name, pwd=student_in.pwd, sno=student_in.sno, clas_id=student_in.clas_id)
    # await student.save()  # 插入到数据库student表;必须要加await
    # 方式2
    student = await Student.create(name=student_in.name, pwd=student_in.pwd, sno=student_in.sno,
                                   clas_id=student_in.clas_id)
    print(student, type(student))
    return student

  

 

posted @ 2026-02-04 21:10  全栈测试笔记  阅读(54)  评论(0)    收藏  举报
浏览器标题切换
浏览器标题切换end