如何设置“/*”路径以捕获FastAPI中的所有路由?

How to set "/*" path to capture all routes in FastAPI?

ExpressJS 一样,app.get("/*") 适用于所有路线。

我的代码-

from typing import Optional
from fastapi import FastAPI

app = FastAPI()


@app.get('/*')
def user_lost():
    return "Sorry You Are Lost !"

我试过了但是网页结果显示{"detail":"Not Found"}
如何在 FastApi 中执行 same?

您可以使用 /{full_path} 捕获一条路径中的所有路由(参见 documentation)。

@app.route("/{full_path:path}")
async def capture_routes(request: Request, full_path: str):
    ...

我将 Yagiz 的代码编辑为:

@app.get("/{full_path:path}")
async def capture_routes(request: Request, full_path: str):
   ...

最好在 https://sureshdsk.dev/how-to-implement-catch-all-route-in-fast-api

中解释

唯一的附加评论是;

如果你想混合 catch-all 并处理某些路径,如 /hello 或 /api ..确保 catch all 方法定义在最后....路由定义的顺序很重要