我正在使用 FastAPI,我希望有两条引用相同函数的路由。我需要其中一种情况下的值来自路径操作,而在另一种情况下,我需要将其生成为依赖项。
下面是我认为可行的方法,但是
/inbound
情况会生成 422 Unprocessable entity
错误。
def middleware():
return {"wako_id": "123"}
def test(request: Request, wako_id: str):
return wako_id
authorized_router.add_api_route(
"/inbound",
test,
dependencies=[Depends(middleware)],
methods=["GET"]
)
authorized_router.add_api_route(
"/outbound/{wako_id}",
test,
methods=["GET"]
)
您可以在 dependency 函数中将
wako_id
参数声明为 Optional
(有关 FastAPI 中可选参数的更多详细信息和示例,请参阅 this 和 this),然后 检查请求的原始 url 路径 ,如果是 /outbound
,则返回用户指定的 wako_id
值,否则如果调用了 /inbound
路由,则返回您的自定义 wako_id
。
请注意,您还可以有一个
else
语句并返回 JSONResponse(content="wako_id is missing", status_code=400)
(有关如何从 FastAPI 返回 JSON 的更多详细信息,请参阅 这个答案),以防在未传递 /outbound
的情况下调用 wako_id
路由范围。但是,在您的情况下,您不必这样做,因为 wako_id
被声明为 path
参数,并且路径参数是 required。因此,例如,如果用户调用 http://127.0.0.1:8000/outbound
(不带 wako_id
路径参数,例如 /outbound/some_str_id_here
),FastAPI 将自动返回 {"detail":"Not Found"}
错误响应。
最后,我建议您看看这个答案,这个答案,以及这个答案,这个答案和这个答案,以便更好地理解如何使用
Dependencies
FastAPI,以及如何将对象或值从 dependency
函数传递到端点,以防您对整个路由器或特定路由使用全局 dependency
,使用 dependencies
参数(类似于您提供的示例)。否则,您可以在端点的参数上使用 Depends
关键字,并返回对象/值,如下例所示。
from fastapi import FastAPI, Request, APIRouter, Depends
from typing import Optional
app = FastAPI()
router = APIRouter()
def get_wako_id(request: Request, wako_id: Optional[str] = None):
path = request.scope['root_path'] + request.scope['route'].path
if wako_id and path == '/outbound/{wako_id}':
return wako_id
elif path == '/inbound':
return '123'
def endpoint(wako_id: str = Depends(get_wako_id)):
return wako_id
router.add_api_route("/inbound", endpoint, methods=["GET"])
router.add_api_route("/outbound/{wako_id}", endpoint, methods=["GET"])
app.include_router(router)