You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI对象无default_response_class属性问题求助

FastAPI引入子路由报错:AttributeError: 'FastAPI' object has no attribute 'default_response_class'

问题场景

尝试在主FastAPI路由中引入子路由,主路由代码如下:

from fastapi import FastAPI

from test.main.app.google_calendar_wrapper import app as calendar_manager_router

app = FastAPI()

app.include_router(calendar_manager_router, prefix="/calendar_manager", tags=["calendar_manager"])

@app.get("/")
def root():
    return {"message": "Home Page"}

执行启动命令:

uvicorn test.main.app.webhooks.router:app --port 8050 --reload

触发错误:

AttributeError: 'FastAPI' object has no attribute 'default_response_class'

文件结构

test
| main
  | app
    |  google_calendar_wrapper
      | endpoints.py
      | __init__.py
    |  webhooks
      |  router.py

已尝试方案

  • 不引入该子路由时,应用可正常启动
  • 给google_calendar_wrapper添加/移除__init__.py,添加时尝试导出相关内容,仍报错
  • 两个路由各自独立运行正常,但合并后问题未解决

子路由(calendar_manager_router)原代码

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
    return {"message": "Hello World"}

@app.get("/health")
def health():
    """Api health endpoint."""
    return {"Api is up and running"}

解决方法

核心问题是你把完整的FastAPI应用实例当作子路由传入了include_router方法,但该方法要求传入的是APIRouter实例,而非独立的FastAPI应用。

步骤1:修改子路由代码

将google_calendar_wrapper/endpoints.py中的FastAPI实例替换为APIRouter:

from fastapi import APIRouter

router = APIRouter()

@router.get("/")
def root():
    return {"message": "Hello World"}

@router.get("/health")
def health():
    """Api health endpoint."""
    return {"Api is up and running"}

步骤2:配置子路由导出

在google_calendar_wrapper/__init__.py中添加导出语句:

from .endpoints import router as calendar_manager_router

步骤3:修正主路由导入

修改主路由文件的导入逻辑:

from fastapi import FastAPI

from test.main.app.google_calendar_wrapper import calendar_manager_router

app = FastAPI()

app.include_router(calendar_manager_router, prefix="/calendar_manager", tags=["calendar_manager"])

@app.get("/")
def root():
    return {"message": "Home Page"}

修改完成后重新启动应用,即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:50:22