当前位置: 首页 > news >正文

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

 

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

请求数据:符合要求

main.py

import uvicorn
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoisefrom test_orm.api.student import student_api
from test_orm.settings import TORTOISE_ORMapp = 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 Listfrom fastapi import APIRouter
from pydantic import BaseModel, field_validatorfrom test_orm.models import Studentstudent_api = APIRouter()class StudentIn(BaseModel):name: strpwd: strsno: intclas_id: intcourses: List[int] = []@field_validator("name")def name_must_alpha(cls, value):  # 使用 cls 而不是 selfassert 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):# 方式1student = Student(name=student_in.name, pwd=student_in.pwd, sno=student_in.sno, clas_id=student_in.clas_id)await student.save()  # 插入到数据库student表;必须要加awaitprint(student, type(student))return student

 

接口文档

image

 

请求数据

image

 

响应结果

image

 

image

 

数据库新增id为3的数据

image

 

查询添加的数据

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

from typing import Listfrom fastapi import APIRouter
from pydantic import BaseModel, field_validatorfrom test_orm.models import Student, Coursestudent_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# 方式2student = 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

  

 

http://www.jsqmd.com/news/342925/

相关文章:

  • 远程桌面方案全对比:RDP/VNC/Parsec怎么选 - 指南
  • 2026首发版,自学AI大模型的正确顺序:最新最全学习路线全解析
  • 如何用Agentic AI 提升客户服务质量?提示工程架构师的5个技巧
  • stm32的ADC模块在进行单通道ADC测量时,悬空接地电压在OLED显示屏上显示为3.3V,而不是实际的电压值,如何解决?
  • LiveChart2踩过的坑
  • AI产品经理深度转型指南!
  • RAG上下文构建完全指南:从召回策略到最佳实践,一篇搞定!建议收藏
  • ModelEngine智能编排:构建下一代AI驱动的创新应用生态
  • 初学go - 2 - 文件
  • 用 Hashids 优雅解决 C 端自增 ID 暴露问题
  • ue metahuman自动绑定
  • 全球股市估值与脑机接口在情绪管理中的应用
  • MegaFlow:大模型时代Agent训练的分布式编排系统详解
  • 大模型RAG管道优化:“过度设计“的邻居扩展策略是否真的有效?
  • 华为OD技术面真题 - Mysql相关 - 4
  • 把90!输出到屏幕上(二)
  • Agent产品经理10大高频问题详解,附专业回答模板,建议收藏!
  • 电子抑振控制实验中MATLAB+示波器的用法-PART-RIGOL-电磁制振
  • 【学习笔记】【算法】线段树进阶
  • AI大模型应用开发从入门到精通:2026大模型应用开发最全学习路线
  • 全国镍材优质厂家有哪些?优先选哪些维度筛选? - 非研科技
  • 小红书美妆推广服务商:传声港新媒体平台美妆行业精准营销白皮书 - 速递信息
  • 大数据时代下 Kafka 的核心原理深度剖析
  • 江浙沪蟹粉专家常见问题解答(2026最新) - 速递信息
  • 振动下机械臂鲁棒快控制-EXP-振动控制-机械臂
  • 【课程设计/毕业设计】基于Django+大数据爬虫的短视频推荐系统的设计与实现基于django+大数据平台的短视频推荐系统设计与实现【附源码、数据库、万字文档】
  • AI原生语音识别避坑指南:常见问题与解决方案
  • 2026年口碑好的全自动离心机,拉袋离心机,平板离心机厂家优质供应商榜单 - 品牌鉴赏师
  • 计算机大数据毕设实战-基于django+大数据平台的食物营养成分分析与推荐系统的设计与实现基于Django打造食物营养数据可视化分析系统【完整源码+LW+部署说明+演示视频,全bao一条龙等】
  • AI元人文:哪吒——认知异化时代的元神话与行动纲领