繁体   English   中英

"FastAPI - 模块“app.routers.test”没有属性“路由”"

[英]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

但我不断收到以下错误:

文件“/Users/Desktop/test-service/venv/lib/python3.8/site-packages/fastapi/routing.py”,第 566 行,在 include_router 中用于 router.routes 中的路由:AttributeError: module 'app.routers.测试'没有属性'路由'python-BaseException

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

我想你想要:

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

而不是:

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

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

问题出在你的进口上,你的进口应该像

from parentfolder.file import routes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM