![](/img/trans.png)
[英]AttributeError: module 'test' has no attribute 'randhiletter'
[英]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.