【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 分钟前
python-字符排列问题
数据结构·python·算法
测试199829 分钟前
使用Selenium进行网页自动化
自动化测试·软件测试·python·selenium·测试工具·自动化·测试用例
小黄酥30 分钟前
Python学习笔记--模块
笔记·python·学习
UvwxyZ66631 分钟前
python日志记录与命令行交互
开发语言·python
TechQuester43 分钟前
OpenAI 刚刚推出 o1 大模型!!突破LLM极限
人工智能·python·gpt·算法·chatgpt
西农小陈1 小时前
python-简单的数据结构
数据结构·python·算法
无敌开心1 小时前
Django-Celery-Flower实现异步和定时爬虫及其监控邮件告警
爬虫·python·django
api771 小时前
1688商品详情API返回值中的售后保障与服务信息
java·服务器·前端·javascript·python·spring·pygame
疑惑的杰瑞1 小时前
[乱码]确保命令行窗口与主流集成开发环境(IDE)统一采用UTF-8编码,以规避乱码问题
java·c++·vscode·python·eclipse·sublime text·visual studio
喵手1 小时前
Java零基础-多态详解
java·开发语言·python