【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": "作品"}


相关推荐
鲨鱼辣钊8 分钟前
【FastAPI筑基-Day19】APScheduler定时任务全实战|自动执行、动态启停、后台常驻
java·spring·fastapi
傲笑风6 小时前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
维基框架6 小时前
WIKI 知识库 v1.1.1 正式发布
人工智能·python
谢白羽10 小时前
SGLang的AWQ量化笔记
笔记·python·sglang
迷迭香yy11 小时前
基金档案数据工程实战从收入分析到持仓穿透的Python解析 IG50免费开源股票数据API接口
开发语言·python
清水白石00811 小时前
Python 类型设计深度解析:TypedDict 能否替代 dataclass?从 JSON 数据边界到 API 设计的最佳实践
java·python·json
️学习的小王11 小时前
Git项目提交忽略文件怎么做?以Python项目为例,详解.gitignore
git·python·elasticsearch
前端 贾公子11 小时前
第09章:上下文与记忆 (6)
开发语言·前端·python
evans在进步11 小时前
Java 常用设计模式入门:建造者、工厂、单例、外观与代理
java·python·设计模式
jayson.h12 小时前
PDF 合并+添加页码 相关库、类、函数
开发语言·前端·python