1

我有一个主要调用外部 API 的 FastAPI 应用程序。在某些情况下,路径操作将对同一主机进行多次调用。出于这个原因,我想为每个请求使用一个 httpx AsyncClient。

执行此操作的正确方法似乎是在依赖范围内让客户:

async def get_client(token: str):

    client = httpx.AsyncClient(headers={"Authorization": f"Bearer {token}"})
    
    try:
        yield client
    
    finally:
        await client.aclose()

不过,我不想将此依赖项添加到每个路径操作中,纯粹是为了不在整个代码中重复自己。但是,在阅读了https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/之后,似乎全局依赖项仅在该依赖项正在执行某些操作而不是返回某些内容时才适用。我看不到每个路径操作如何访问产生的客户端,除非为该特定路径操作明确指定依赖关系。我也看不到如何将令牌传递给依赖项。

即这将不允许我的路径操作使用客户端:

app.include_router(
    router,
    prefix="/api",
    dependencies=Depends(get_client)
)

但这将:

@router.get("/", status_code=status.HTTP_200_OK)
async def get_something(request: Request, client: httpx.AsyncClient = Depends(get_client)):

    client.get('www.google.com')

如果该依赖项返回路径操作所需的内容,是否可以使用全局依赖项?

4

0 回答 0