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


相关推荐
樱花落木兰28 分钟前
Redis 消息队列的可靠性演进:从 List、Pub/Sub 到 Stream 消费者组,以及 8.x 版本改变了什么
java·开发语言·经验分享·redis·分布式·python·软件工程
峯58029 分钟前
一文学习FastAPI
学习·fastapi
mumu15735 分钟前
快速上手大模型推理vllm
人工智能·python·大语言模型·agent·vllm
明天会有多晴朗35 分钟前
从零手写 Transformer!一个 Python 文件跑通英译中(PyTorch 附完整源码)
人工智能·pytorch·python·深度学习·transformer
ragnwang10 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
王中阳Go10 小时前
后端转 Agent 岗面试怎么答:8 个高频问题与应答口径
人工智能·后端·python·大语言模型
weixin_3077791311 小时前
RAG 面试陷阱——混合检索并非无条件优越:一个条件反转实验
人工智能·python·面试·职场和发展
云和数据.ChenGuang11 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
荣码14 小时前
长上下文与大文档处理:200页PDF怎么喂给AI,我踩了4个坑
java·python
databook15 小时前
Pandas 与 Polars:语法、性能和资源占用方面的对比
python·数据分析·pandas