簡體   English   中英

在 FastAPI 中匹配路由時如何失敗

[英]How can I fall-through when matching routes in FastAPI

我正在嘗試將 FastAPI 應用程序 + 前端部署在一個 Docker 容器中,所以我不想添加 NginX 或另一個 web 服務器作為它的設置。

我的路線應該是這樣的:

/ <-- should serve index.html
/{id} <-- should serve index.html, but only when {id} is int
/css/* <-- should serve files from css directory
/... <-- a few other static files (e.g. /service-worker.js)

/api/<whatever> <-- these are the fastAPI routes

因此,一種解決方案是匹配 /{id} 當它是 int 時匹配,而不是失敗時匹配。 或者,如果有一種方法可以將所有內容都作為 static 文件提供,除了 /api 調用,那也可以。

目前我的 main.py 中有這樣的內容:

@app.get('/api/items')
async def get_items():
    return [{'id':1, 'name': 'a'}, {'id':2, 'name': 'b'}]

@app.get('/{id}')
async def root():
    with open('html/index.html', 'r') as f:
        return HTMLResponse(f.read())

app.mount("/", StaticFiles(directory="dist"), name="static")

但是當我導航到“/”時,我得到了 404。 我用uvicorn main:app服務它。

任何幫助表示贊賞。

如文檔所述,您需要“掛載”一個 static 文件路徑。 您可以使用您喜歡的名稱設置文件夾,並在 URL 上添加前綴。

然后它會在每次頁面更改時刷新,因此您需要某種方式在客戶端中存儲訪問令牌/會話數據。 此外,從客戶端到 API 的每個調用都會 go。

下面是有關 static 文件的文檔的鏈接:

https://fastapi.tiangolo.com/tutorial/static-files/#static-files

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM