【发布时间】:2021-03-03 07:15:35
【问题描述】:
我正在尝试使用 FastAPI 设置应用程序,但不断收到这个我无法理解的错误。我的main.py文件如下:
from fastapi import FastAPI
from app.routers import test
app = FastAPI()
app.include_router(test, prefix="/api/v1/test")
在我的routers/test.py 文件中,我有:
from fastapi import APIRouter, File, UploadFile
import app.schemas.myschema as my_schema
router = APIRouter()
Response = my_schema.Response
@router.get("/", response_model=Response)
def process(file: UploadFile = File(...)):
# Do work
但我不断收到以下错误:
文件 "/Users/Desktop/test-service/venv/lib/python3.8/site-packages/fastapi/routing.py", 第 566 行,在 include_router 中 对于router.routes中的路由:AttributeError:模块'app.routers.test'没有属性'routes' python-BaseException
我无法理解这一点,因为我可以在示例应用 here 中看到类似的操作。
【问题讨论】:
-
app.routers.test有routes属性吗?app.routers.test是什么?是路由器吗?我的机器上没有这些东西,所以我无法查看,但我猜app.include_router期望的第一个参数与test不同。 (这是动态类型语言的缺点) -
它没有路由属性,但示例也没有。是的,它是一个路由器。 test.py 的内容本身有问题
-
我仍然看不到您在哪里定义传递给
app.include_router的test是什么。如果是test.py,那么它是一个模块,而不是一个普通的 Python 对象。所以如果这是真的,你可能想要app.include_router(test.router, prefix="/api/v1/test")吗?更新:啊,我之前错过了这个。错误消息告诉您app.routers.test是一个 Python 模块。我怀疑这就是你想要传递给任何东西的东西。现在我比以往任何时候都更想通过test.router而不是test。 -
完全正确。我的坏