I am trying to setup an app using FastAPI but keep getting this error which I can't make sense of. My main.py
file is as follows:
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:
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
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
.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.