【Fastapi】使用APIRouter做路由管理

使用APIRouter做路由管理

gitee https://gitee.com/zz1521145346/fastapi_frame.git

github https://github.com/zz001357/fastapi_frame.git

通过FastAPI()实例化一个app对象之后,有一个include_router的方法。通过查看include_router的源码后发现,有两种方法,一种self(也就是在本身app这个对象下添加路由),一种是使用router。通过APIRouter实例化一个对象暂且称为api。将api作为app的include_router方法里的(router=api).然后由api管理路由

方法一

main.py中

复制代码
	app = FastAPI()
    app.include_router(project.router)
    app.include_router(about.router)

about.py中

复制代码
	from fastapi import APIRouter
	router = APIRouter()
	@router.get("/api/about")
	async def u_test():
	return {"message": "关于"}


方法二

main.py中

复制代码
from api.router import api
app = FastAPI()
app.include_router(router=api)

router.py中

复制代码
from fastapi import APIRouter
from api import user
api = APIRouter()
api.include_router(user.router)
api.include_router(works.router)
__all__ = ['api']

works.py中

复制代码
from fastapi import APIRouter
router = APIRouter()
@router.get("/api/works")
async def u_test():
return {"message": "作品"}


相关推荐
大模型码小白3 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧3 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
C^h7 小时前
python函数学习
人工智能·python·机器学习
Fanta丶7 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬7 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent
兜客互动8 小时前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_538601978 小时前
智能体测开Day30pytest测试框架
python
MC皮蛋侠客8 小时前
uv 系列(七):CI/CD、Docker 与私有索引——生产级交付
python·ci/cd·docker·uv
邪神与厨二病8 小时前
牛客周赛 Round 153
python·算法
yaoxin5211238 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python