尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

day2作业笔记

day2作业笔记
📅 发布时间:2026/7/22 9:28:47

模型

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':'标签删除成功'}

相关新闻

  • OpenClaw AI框架安装指南与性能优化技巧
  • 计算机网络:自顶向下方法 学习笔记
  • F28379D 下载后 VOFA+ 无数据、Reset 后恢复:一次 TZ 中断误触发排查记录

最新新闻

  • 挑战零代码做游戏:我用QClaw搓了个世界杯颠球挑战
  • 中小企业GEO轻量化方案:低成本高回报的实战路径
  • 2026 襄阳黄金回收行业第三方实测测评|7 月大盘行情解析 - 不晚生活号
  • AI与大模型新闻日报 | 2026-07-22
  • 《爱人》预告片剪辑解析:情绪节奏与符号隐喻的视听语言设计
  • 运维转大模型:把脚本换成 Agent,我踩过的坑都在权限和日志里

日新闻

  • AI云原生实战05-金融AI上云最难的不是技术,是“不出事“——TCE银行风控架构拆解
  • 2026年GEOSEO优化公司选型深度测评:五大硬核标准严选,这六家重塑搜索增长新格局 - 品牌前沿专家
  • **核验!2026年7月卡地亚香港**售后网点地址及服务电话公告 - 卡地亚服务中心

周新闻

  • SaaS软件行业GEO实践:AI搜索时代的品牌可见性与获客新路径
  • 什么是PCTFE?医药高端包装的“防潮王牌“材料
  • 【JVM调优实战】16-可视化利器-JConsole-VisualVM-JMC

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号