Python FastAPI 基本路径控制

Jim*_*yNJ 9 python fastapi

当我使用 FastAPI 时,如何指定 Web 服务的基本路径?

换句话说 - FastAPI 对象是否有参数可以将端点和我定义的任何其他端点设置为不同的根路径?

例如,如果我的代码带有root下面的虚假参数,它会将我的/my_path端点附加到/my_server_path/my_path?

from fastapi import FastAPI, Request

app = FastAPI(debug = True, root = 'my_server_path') 

@app.get("/my_path")
def service( request : Request ):
    return { "message" : "my_path" }
Run Code Online (Sandbox Code Playgroud)

Han*_*bel 14

您可以使用APIRouter并在添加路径后将其添加到应用程序中:

from fastapi import APIRouter, FastAPI

app = FastAPI()

prefix_router = APIRouter(prefix="/my_server_path")

# Add the paths to the router instead
@prefix_router.get("/my_path")
def service( request : Request ):
    return { "message" : "my_path" }

# Now add the router to the app
app.include_router(prefix_router)
Run Code Online (Sandbox Code Playgroud)

当先添加路由器然后添加路径时,它现在可以工作了。看来路径不是动态检测的。

注意:路径前缀必须以/以下开头(感谢 Harshal Perkh)