【问题标题】:FastAPI - module 'app.routers.test' has no attribute 'routes'FastAPI - 模块“app.routers.test”没有属性“路由”
【发布时间】: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.testroutes 属性吗? app.routers.test 是什么?是路由器吗?我的机器上没有这些东西,所以我无法查看,但我猜app.include_router 期望的第一个参数与test 不同。 (这是动态类型语言的缺点)
  • 它没有路由属性,但示例也没有。是的,它是一个路由器。 test.py 的内容本身有问题
  • 我仍然看不到您在哪里定义传递给 app.include_routertest 是什么。如果是test.py,那么它是一个模块,而不是一个普通的 Python 对象。所以如果这是真的,你可能想要app.include_router(test.router, prefix="/api/v1/test") 吗?更新:啊,我之前错过了这个。错误消息告诉您app.routers.test 是一个 Python 模块。我怀疑这就是你想要传递给任何东西的东西。现在我比以往任何时候都更想通过test.router 而不是test
  • 完全正确。我的坏

标签: python fastapi


【解决方案1】:

我想你想要:

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

而不是:

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

【讨论】:

    【解决方案2】:

    不,您不能直接从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,
            ...
        )
    

    【讨论】:

      【解决方案3】:

      问题在于你的import语句,你的import应该是这样的

      from parentfolder.file import attribute
      

      困惑?不用担心让我让它变得简单 您用于定义和分配给 APIRouter 的任何变量都将成为您的属性。 在 test.py 的示例中,您将路由定义为属性routes = APIRouter() 这意味着如果您想在任何其他地方使用它,您需要执行以下操作

      from routers.test import routes
      

      祝你好运

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 2014-04-15
        • 2020-06-04
        • 2021-12-24
        • 2015-05-08
        • 2020-10-17
        • 2020-10-03
        相关资源
        最近更新 更多