简体   繁体   English

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

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

I am trying to setup an app using FastAPI but keep getting this error which I can't make sense of.我正在尝试使用 FastAPI 设置应用程序,但不断收到这个我无法理解的错误。 My main.py file is as follows:我的main.py文件如下:

from fastapi import FastAPI
from app.routers import test

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

And in my routers/test.py file I have:在我的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

But I keep getting the following error:但我不断收到以下错误:

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

I cant make sense of this as I can see something similar being done in the sample app here .我无法理解这一点,因为我可以在此处的示例应用程序中看到类似的操作。

I think you want:我想你想要:

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

rather than:而不是:

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

No, you can not directly access it from the app , because when you add an instance of APIRouter with include_router , FastAPI adds every router to the app.routes .不,您不能直接从app访问它,因为当您使用include_router添加 APIRouter 实例时,FastAPI 会将每个路由器添加到app.routes

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

It does not add the route to the application instead it adds the routes, but since your router is an instance of APIRouter, you can reach the routes from that.它不会向应用程序添加路由,而是添加路由,但由于您的路由器是 APIRouter 的一个实例,因此您可以从中访问路由。

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

the problem lies in your import, your import should be like问题出在你的进口上,你的进口应该像

from parentfolder.file import routes

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

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