跳至內容

子應用程式 - 掛載

如果您需要兩個獨立的 FastAPI 應用程式,各自擁有獨立的 OpenAPI 和文件 UI,您可以建立一個主應用程式並「掛載」一個(或多個)子應用程式。

掛載 FastAPI 應用程式

「掛載」是指在特定路徑下新增一個完全「獨立」的應用程式,然後由該子應用程式中宣告的*路徑操作*來處理該路徑下的所有內容。

頂層應用程式

首先,建立主要的頂層 FastAPI 應用程式及其*路徑操作*。

from fastapi import FastAPI

app = FastAPI()


@app.get("/app")
def read_main():
    return {"message": "Hello World from main app"}


subapi = FastAPI()


@subapi.get("/sub")
def read_sub():
    return {"message": "Hello World from sub API"}


app.mount("/subapi", subapi)

子應用程式

接著,建立您的子應用程式及其*路徑操作*。

這個子應用程式只是另一個標準的 FastAPI 應用程式,但它將會被「掛載」。

from fastapi import FastAPI

app = FastAPI()


@app.get("/app")
def read_main():
    return {"message": "Hello World from main app"}


subapi = FastAPI()


@subapi.get("/sub")
def read_sub():
    return {"message": "Hello World from sub API"}


app.mount("/subapi", subapi)

掛載子應用程式

在您的頂層應用程式 app 中,掛載子應用程式 subapi

在這個例子中,它將會掛載在 /subapi 路徑下。

from fastapi import FastAPI

app = FastAPI()


@app.get("/app")
def read_main():
    return {"message": "Hello World from main app"}


subapi = FastAPI()


@subapi.get("/sub")
def read_sub():
    return {"message": "Hello World from sub API"}


app.mount("/subapi", subapi)

檢查自動 API 文件

現在,使用您的檔案執行 fastapi 命令。

$ fastapi dev main.py

<span style="color: green;">INFO</span>:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

並在 http://127.0.0.1:8000/docs 開啟文件。

您將會看到主應用程式的自動 API 文件,其中僅包含其自身的*路徑操作*。

然後,在 http://127.0.0.1:8000/subapi/docs 開啟子應用程式的文件。

您將會看到子應用程式的自動 API 文件,其中僅包含其自身的*路徑操作*,所有操作都在正確的子路徑前綴 /subapi 之下。

如果您嘗試與這兩個使用者介面中的任何一個互動,它們都能正常運作,因為瀏覽器將能夠與每個特定的應用程式或子應用程式通訊。

技術細節:root_path

當您如上所述掛載子應用程式時,FastAPI 將會使用 ASGI 規範中稱為 root_path 的機制來傳達子應用程式的掛載路徑。

如此一來,子應用程式便會知道要將該路徑前綴用於文件 UI。

而且子應用程式也可以擁有自己的掛載子應用程式,並且一切都能正常運作,因為 FastAPI 會自動處理所有這些 root_path

您將會在關於代理伺服器後方的章節中了解更多關於 root_path 以及如何明確使用它的資訊。