【问题标题】:How to set "/*" path to capture all routes in FastAPI?如何设置“/*”路径以捕获 FastAPI 中的所有路由?
【发布时间】:2021-02-15 04:45:50
【问题描述】:

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 中做到相同

【问题讨论】:

  • 你已经尝试过什么?请参阅How to Ask
  • 我试过了,还是不行。

标签: python fastapi


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

我将 Yagiz 的代码编辑为:

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

【讨论】:

  • 请显示问题所在的代码行。更精确。
  • 从 fastapi 导入 Request 类。使用:from fastapi import Request
【解决方案3】:

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

唯一的附加评论是;

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

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2020-11-14
    • 2021-08-13
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2011-04-29
    相关资源
    最近更新 更多