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

day2作业笔记

模型

models/articles.py

from tortoise import Model,fields class Category(Model): id=fields.IntField(pk=True,auto_increment=True,description='分类ID') name=fields.CharField(max_length=50,description='分类名称') class Meta: table='db_category' class Author(Model): id=fields.IntField(pk=True,auto_increment=True,description='作者ID') name=fields.CharField(max_length=50,description='作者名称') class Meta: table='db_author' class Article(Model): id=fields.IntField(pk=True,auto_increment=True,description='文章ID') title=fields.CharField(max_length=200,description='文章标题') content=fields.TextField(description='文章内容') summary=fields.CharField(max_length=200,description='文章摘要') category=fields.ForeignKeyField('models.Category',description='分类') author=fields.ForeignKeyField('models.Author',description='作者') tags=fields.ManyToManyField('models.Tag',related_name='articles',description='标签') view_count=fields.IntField(default=0,description='文章浏览量') status=fields.SmallIntField(choices=[(0,'草稿'),(1,'已发布')],default=0,description='文章状态') class Meta: table='db_article'
models/tags.py
from tortoise import Model,fields class Tag(Model): id=fields.IntField(pk=True,auto_increment=True,description='标签ID') name=fields.CharField(max_length=50,description='标签名称') color=fields.CharField(max_length=20,default='#409EFF',description='标签颜色') class Meta: table='db_tag'

接口

1.分类增删改查功能

from fastapi import APIRouter, HTTPException from pydantic import BaseModel from apps.models import Category category_router=APIRouter() @category_router.get('/category/',tags='获取所有分类') async def get_all_category(): categories=await Category.all() return categories class CategoryCreateRequest(BaseModel): name:str @category_router.post('/category/',tags='新建分类') async def add_category(request:CategoryCreateRequest): category=await Category.create(**request.model_dump()) return category class CategoryUpdateRequest(BaseModel): name:str @category_router.put('category/{id}',tags='编辑分类') async def update_category(id:int,request:CategoryUpdateRequest): category=await Category.get_or_none(id=id) if not category: raise HTTPException(status_code=404,detail='分类不存在') await category.update_from_dict(request.model_dump()).save() return category @category_router.delete('category/{id}',tags='删除分类') async def delete_category(id:int): category=await Category.get_or_none(id=id) await category.delete() return {'message':'删除成功','id':id}

2.文章增删改查功能

from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel, computed_field from tortoise.contrib.pydantic import pydantic_model_creator from apps.models import Article, Tag from utils.jwt import login_required article_router=APIRouter() ArticleOut=pydantic_model_creator(Article,name='ArticleOut') class TagOut(BaseModel): id:int name:str color:str class CategoryOut(BaseModel): id:int name:str class AuthorOut(BaseModel): id:int name:str class ArticleListOut(BaseModel): id:int title:str summary:str view_count:int status:int category:CategoryOut author:AuthorOut tags:list[TagOut] @computed_field @property def status_text(self)->str: return '草稿' if self.status==0 else '已发布' @article_router.get('/article/',tags='文章列表(条件筛选)') async def article_list(user=Depends(login_required),category:int=None,title:str=None,): query=Article.all() if category is not None: query=query.filter(category_id=category) if title is not None: query=query.filter(title__contains=title) articles = await query.prefetch_related('category', 'author', 'tags') return [ ArticleListOut( id=a.id, title=a.title, summary=a.summary, view_count=a.view_count, status=a.status, category=CategoryOut(id=a.category.id, name=a.category.name), author=AuthorOut(id=a.author.id, name=a.author.name), tags=[TagOut(id=t.id, name=t.name, color=t.color) for t in a.tags] ) for a in articles ] class ArticleCreateRequest(BaseModel): title:str content:str summary:str category:int tags:list[int] status:int=0 @article_router.post('/article/',tags='新建文章') async def create_article(request:ArticleCreateRequest,user=Depends(login_required)): tag_ids=request.tags data=request.model_dump(exclude={'tags'}) article=await Article.create(**data,author_id=user.id) if tag_ids: tags=await Tag.filter(id__in=tag_ids) await article.tags.add(*tags) return await ArticleOut.from_tortoise_orm(article) class ArticleUpdateRequest(BaseModel): title:str content:str summary:str category:int tags:list[int] status:int=0 @article_router.put('/article/{id}',tags='编辑文章') async def update_article(id:int,request:ArticleUpdateRequest,user=Depends(login_required)): article_id=await Article.get_or_none(id=id) if not article_id: raise HTTPException(status_code=404,detail='文章不存在') tag_ids = request.tags data = request.model_dump(exclude={'tags'}, exclude_none=True) await article_id.update_from_dict(data).save() if tag_ids is not None: tags = await Tag.filter(id__in=tag_ids) await article_id.tags.clear() await article_id.tags.add(*tags) return await ArticleOut.from_tortoise_orm(article_id) @article_router.delete('/article/{id}',tags='删除文章') async def delete_article(id:int,user=Depends(login_required)): article_id=await Article.get_or_none(id=id) if not article_id: raise HTTPException(status_code=404,detail='文章不存在') await article_id.delete() return {'message':'删除成功'}

3.标签增删查功能

from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from apps.models import Tag tag_router=APIRouter() @tag_router.get('/tag/',tags='获取所有标签') async def tag_list(): tags=await Tag.all() return tags class TagCreateRequest(BaseModel): name:str color:str @tag_router.post('/tag/',tags='创建标签') async def add_tag(request:TagCreateRequest): exists=await Tag.filter(name=request.name).first() if exists: raise HTTPException(status_code=400,detail='标签名称已存在') tag=await Tag.create(**request.model_dump()) return tag @tag_router.delete('/tag/{id}',tags='删除标签') async def delete_tag(id:int): tag=await Tag.get_or_none(id=id) await tag.delete() return {'message':'标签删除成功'}
http://www.jsqmd.com/news/1240307/

相关文章:

  • 广州闲置黄金变现攻略:足金、18K金、金条回收规则差异一文分清 - 奢侈品回收评测
  • 2026青岛技术院校推荐:五大产教融合**院校家长选校实战手册 - 增长观测局
  • 昇腾NPU大模型推理优化:DeepSeek-V3.2-Exp性能突破
  • OneDev vs GitLab:轻量级DevOps平台选型决策指南
  • 程序员必备资源大全:工具链与学习平台全指南
  • Cursor AI编程工具:提升开发效率的实战解析
  • HTTP 404错误详解:原理、影响与处理策略
  • OpenClaw AI框架安装指南与性能优化技巧
  • 计算机网络:自顶向下方法 学习笔记
  • AI编程工具选择指南:超越月费的全方位评估
  • F28379D 下载后 VOFA+ 无数据、Reset 后恢复:一次 TZ 中断误触发排查记录
  • 企业文档管理系统怎么选?2026年采购必须关注这8项能力
  • 2026战略管理咨询公司**:十大专业机构为集团企业发展指明方向 - 运营方法论
  • 椭圆曲线加密算法(ECC)种子破解与安全验证
  • 2026年7月雷达中国区售后服务网络更新优化 全国60+门店地址及电话汇总 - 亨得利中国服务中心
  • 腾讯混元Hy3模型:MoE架构驱动的AI Agent开发实战指南
  • librdkafka中文文档翻译实践与关键技术解析
  • AI测试开发:从传统测试到智能测试的转型指南
  • Spring Security构建电商低代码平台认证授权体系
  • SolidWorks配合关系管理与删除技巧详解
  • 深入解析TI EMIFA:NAND Flash状态监控、中断与电源管理实战
  • 2026 东莞市全域防水补漏哪家靠谱?覆盖 32 镇街园区的正规防水修缮品牌甄选指南.doc - 资讯在线
  • HarmonyOS应用开发实战:萌宠日记 - 日记编辑器整体布局设计
  • 2026年贵阳有哪些高压铝电缆厂家可以选择? - 企业推荐官
  • OkHttp核心原理与性能优化实战指南
  • Jeecg导出excel代码
  • 海风、万人大合唱,和一条不能断的“通讯线“—— 乾元通多链路聚合设备在今夏青岛演唱会场次落地思考
  • DeepMind AGI演进路径:从游戏智能到通用人工智能的技术突破
  • 影视预告片制作全流程指南:从素材管理到输出规范
  • Unity URP屏幕受伤效果:手写Shader实现沉浸式后处理特效