You need to enable JavaScript to run this app. FastAPI调用include_router报app.routers.test无routes属性错误
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI调用include_router报app.routers.test无routes属性错误

问题根因

报错的核心是你传给app.include_router()的对象不对:

  • 当前main.py里from app.routers import test拿到的是app/routers/test.py整个Python模块文件,不是模块内部定义的APIRouter实例
  • 你参考的官方示例项目,实际导入逻辑是取出各接口文件内部定义的APIRouter实例,并非导入整个py模块
  • FastAPI的include_router()方法要求传入的是APIRouter类实例,这类实例才会自带routes属性存储注册的路由列表,普通Python模块没有这个属性,所以触发AttributeError: module 'app.routers.test' has no attribute 'routes'
具体修正方案

两种改法选一个即可:

  • 方案1:修改main.py的导入逻辑,直接导入test模块内部定义的router实例:
from fastapi import FastAPI
# 替换原来的 from app.routers import test 语句
from app.routers.test import router

app = FastAPI()
# 把include_router的参数替换为导入得到的router实例
app.include_router(router, prefix="/api/v1/test")
  • 方案2:保留现有main.py的导入语句,在调用include_router时明确取出test模块里的router对象:
from fastapi import FastAPI
from app.routers import test

app = FastAPI()
# 传入test模块内部的router属性,而非test模块本身
app.include_router(test.router, prefix="/api/v1/test")
后续潜在问题提醒

改完导入报错后,你现有test.py里的接口定义还会触发运行错误:GET请求不支持UploadFile类型的文件上传参数,等导入问题解决后,记得把接口装饰器的请求方法改成@router.post("/"),否则请求会被FastAPI拦截抛出参数错误。


内容的提问来源于stack exchange,提问作者mifol68042

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 19:45:03