[FastAPI-25]博客接口
import typing
from fastapi import FastAPI, Query, HTTPException, status
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
app = FastAPI(title="Blog CRUD")
blogs = {
1: {
"id": 1,
"title": "blog1",
"body": "This is blog1",
"desc": "desc"
},
2: {
"id": 2,
"title": "blog2",
"body": "This is blog2",
"desc": "desc"
}
}
class Blog(BaseModel):
title: str
body: str
desc: str
class BlogUpdate(Blog):
# 博客编辑的时候不是必选项
title: typing.Optional[str] = None
body: typing.Optional[str] = None
desc: typing.Optional[str] = None
@app.get("/blogs",
tags=["博客"],
summary="博客列表接口",
description="page页码,size每页显示的数量"
)
def get_blogs(page: typing.Optional[int] = Query(description="页码", default=1),
size: int = 10):
_blogs_list = list(blogs.values())
return _blogs_list[(page - 1) * size:page * size]
@app.get("/blog",
tags=["博客"],
summary="博客详情页")
def get_blog_id(blog_id: int):
# 字典的get方法效率优于循环遍历
blog = blogs.get(blog_id)
if not blog:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Not found the blog with id :{blog_id}"
)
return blog
@app.post("/blog",
tags=["博客"],
summary="创建新的博客使用POST")
def create_blog(blog: Blog):
blog_id = len(blogs) + 1
# **blog.dict()
# 序列化数据nable_encoder
blogs[blog_id] = {"id": blog_id, **jsonable_encoder(blog)}
return blogs[blog_id]
@app.put("/blog",
tags=["博客"],
summary="整体更新博客使用PUT")
def update_blog(blog_id: int, blog: Blog):
to_update_blog = blogs.get(blog_id)
if not to_update_blog:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Not found the blog with id :{blog_id}"
)
to_update_blog.update(jsonable_encoder(blog))
blogs[blog_id] = to_update_blog
return to_update_blog
@app.patch("/blog",
tags=["博客"],
summary="局部更新博客使用Patch")
def part_update_blog(blog_id: int, blog: BlogUpdate):
to_update_blog = blogs.get(blog_id)
if not to_update_blog:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Not found the blog with id :{blog_id}"
)
to_update_blog.update(**jsonable_encoder(blog,exclude_unset=True))
blogs[blog_id] = to_update_blog
return to_update_blog
@app.delete("/blog",
tags=["博客"],
summary="删除博客使用Delete"
)
def delete_blog(blog_id:int):
to_delete_blog = blogs.get(blog_id)
if not to_delete_blog:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Not found the blog with id :{blog_id}"
)
return blogs.pop(blog_id)
分类:
FastAPI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-03-26 [Oracle]集合运算
2020-03-26 [Oracle]多表连接技术-自然连接
2020-03-26 [Oracle]多表连接技术-交叉连接、非等值连接、等值连接、外连接
2020-03-26 [Oracle]多表连接技术(简介)
2020-03-26 [Oracle]null 空值