FastAPI - 模块 'app.routers.test' 没有属性 'routes'

FastAPI - module 'app.routers.test' has no attribute 'routes'

我正在尝试使用 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

但我不断收到以下错误:

File "/Users/Desktop/test-service/venv/lib/python3.8/site-packages/fastapi/routing.py", line 566, in include_router for route in router.routes: AttributeError: module 'app.routers.test' has no attribute 'routes' python-BaseException

我无法理解这一点,因为我可以在示例应用程序中看到类似的操作 here

不,您不能直接从 app 访问它,因为当您使用 include_router 添加 APIRouter 实例时,FastAPI 会将每个路由器添加到 app.routes

   for route in router.routes:
        if isinstance(route, APIRoute):
            self.add_api_route(
                ...
            )

它不会将路由添加到应用程序,而是添加路由,但由于您的路由器是 APIRouter 的一个实例,您可以从中获取路由。

class APIRouter(routing.Router):
    def __init__(
        self,
        routes: Optional[List[routing.BaseRoute]] = None,
        ...
    )

我想你想要:

app.include_router(test.router, prefix="/api/v1/test")

而不是:

app.include_router(test, prefix="/api/v1/test")

问题出在你的导入语句上,你的导入应该是这样的

from parentfolder.file import attribute

迷茫?别担心,让我简单点 您用来定义和分配给 APIRouter 的任何变量都将成为您的属性。 在 test.py 中的示例中,您将路由定义为属性 routes = APIRouter() 这意味着如果你想在任何其他地方使用它,你需要做如下

from routers.test import routes

祝你好运