FastAPI APIRouter 前缀显示两次。为什么?

问题描述 投票:0回答:1
notecard_router = APIRouter(
prefix = "/notecard",
tags = ['notecard']

嗨,我正在尝试在我的应用程序中包含一个路由器,但由于某种原因,我在 API 路由器中给出的前缀在 API 路径中出现了两次。我不知道为什么会发生这种情况。

python frameworks fastapi
1个回答
0
投票

您的代码没有按照您期望的方式构建路由器。路由器的前缀适用于向其注册的所有路径,在您的情况下:

from fastapi import APIRouter
app = APIRouter(tags=["notecard"], prefix="/notecard")

@app.get("/notecard/index")
async def root():
    ...

最终会重复

notecard
前缀。您的 API 路径实际上变成了
/notecard/notecard/index
(即
/prefix/path
。这里的前缀在路由器级别定义为
notecard
,路径为
notecard/index
。将它们放在一起,我们看到
notecard
重复了。)

相反,在注册子路径时省略路由器前缀,因为您已经在路由器级别定义了前缀。

from fastapi import APIRouter
app = APIRouter(tags=["notecard"], prefix="/notecard")

@app.get("/index")
async def root():
    ...

上述内容将解决您的问题。

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.