【问题标题】:FastAPI: how to access the APIRoute object inside the dependencyFastAPI:如何访问依赖项中的 APIRoute 对象
【发布时间】:2021-01-23 13:21:45
【问题描述】:

我正在使用 FastAPI,而主应用程序使用 include_router 向 fastAPI 应用程序添加额外的路由。

我想在所有路线上添加通用验证。 我在文档中发现,您可以在包含路由器时使用依赖项来实现这一点。

https://fastapi.tiangolo.com/tutorial/bigger-applications/#the-main-fastapi

这很有效,并且正在被所有 http 请求执行。 到目前为止一切都很好!

现在,我想知道在这个通用验证函数内部(在所有路由中使用 Depends() 注入)哪个路由正在调用该函数。

我找到了访问实际请求的方法(使用 fastapi.routing.Request 作为函数的输入参数)但我想访问函数或 APIRoute 本身的名称强>。

from fastapi import FastAPI, Depends
from fastapi.routing import Request, APIRoute

async def check_permission(req: Request, route: APIRoute):
    print("test me")

app = FastAPI()
app.include_router(admin.service_api, dependencies=[Depends(check_permission)])

RuntimeError: no validator found for <class 'fastapi.routing.APIRoute'>

也许这不是一个好主意,我应该以不同的方式来做吗? 非常感谢所有建议。 谢谢。

【问题讨论】:

  • 您可以在您的问题中添加一些代码吗?帮助 rn 有点困难。
  • 好主意。我将其添加到原始问题中。谢谢。
  • 为什么需要函数名或路由名?为什么不使用request.url?

标签: python fastapi starlette


【解决方案1】:

实际上使用 Request 对象是最好的做法,因为它保存了 Request 的全部数据,我看不出不使用它的理由。

即使您为此错误创建了解决方法,您也无法以正确的方式完成这项工作。因为 APIRoute 不是有效的 Pydantic Field 类型,所以我们的 FastAPI 应该为此引发 FastAPIError。

所以答案是:你应该使用 Request 对象。

【讨论】:

  • 主要原因是我想根据记录的操作创建内部逻辑(请参阅OpenAPI standards 中的 operationId)。这比在 URL 上使用一些字符串函数更明确。请求对象似乎没有我可以在不先更改它的情况下解释的单一属性。
  • 那么还有更好的办法!见Path Operation Advanced Configuration
  • 抱歉,我不知道这如何解决我的问题。 operation_id 是 APIRoute 对象的一个​​属性,我无法在 Dependency 对象中访问它。
【解决方案2】:

我想我找到了一种解决方法(通过使用 Request 对象)。 也许它不是很 Pythonic:

async def check_permission(req: Request):
   f = req.scope['endpoint'] 
   # f is the function object of the fast api route endpoint

【讨论】:

    【解决方案3】:

    我希望这会有所帮助,它返回APIRoute 对象,可以在依赖项中使用。我不确定这样做是否安全。 Request 对象应预先注入。

    api_route = next(item for item in request.app.routes if isinstance(item, APIRoute) and item.dependant.cache_key[0] == request.scope['endpoint'])
    

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多