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

Aka*_*aik 3 python fastapi

与 中一样ExpressJSapp.get("/*")适用于所有路线。

我的代码 -

from typing import Optional
from fastapi import FastAPI

app = FastAPI()


@app.get('/*')
def user_lost():
    return "Sorry You Are Lost !"
Run Code Online (Sandbox Code Playgroud)

我尝试过,但网页结果显示{"detail":"Not Found"}
How can I do the same in FastApi?

Yag*_*nci 6

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

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

  • 在最新版本中,这已从“app.route”更改为“app.api_route” https://github.com/tiangolo/fastapi/issues/819#issuecomment-569222914 (2认同)