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


相关推荐
skilllite作者10 分钟前
SkillLite 多入口架构实战:CLI / Python SDK / MCP / Desktop / Swarm 一页理清
开发语言·人工智能·python·安全·架构·rust·agentskills
ZC跨境爬虫25 分钟前
批量爬取小说章节并优化排版(附完整可运行脚本)
前端·爬虫·python·自动化
ths51227 分钟前
Python 正则表达式实战指南:从入门到精通(12 个高频案例)(三)
python·正则表达式
ZC跨境爬虫27 分钟前
海南大学交友平台登录页开发实战day4(解决python传输并读取登录信息的问题)
开发语言·前端·python·flask·html
Wyawsl28 分钟前
Python操作MySQL数据库
数据库·python·mysql
SuperEugene36 分钟前
Python 异步 async/await:为什么 AI 框架大量使用?| 基础篇
开发语言·人工智能·python
SMF191942 分钟前
【uv】Python包管理器uv安装和应用
开发语言·python·uv
gergul42 分钟前
在llama-cpp-python中使用自己编译的llama.cpp,解决pip install llama-cpp-python报错
python·llama·llama.cpp·llamacpppython
深蓝轨迹42 分钟前
#Python零基础机器学习入门教程
人工智能·python·机器学习
蓝色的杯子44 分钟前
Python面试30分钟突击掌握-LeetCode1-Array
开发语言·python·面试