如何在 FastAPI 中获取定义的路由路径?

问题描述

我在 server.py 中定义了我的 FastAPI 应用

app = FastAPI(
debug=True,title="Microservice for APIs",description="REST APIs",version="0.0.1",openapi_url="/v3/api-docs",middleware=[
    Middleware(AuthorizationMiddleware,authorizor=Auth())
]) 

__init__.py 中,我定义了路线

from fastapi import APIRouter
api_router = APIRouter()
api_router.include_router(impl_controller.router,prefix="/impl/data",tags=["APIs for Impl Management"])

impl_controller.py中,我定义了这样的路由

@router.get('{id}/get_all')
def hello_world():
    return {"msg": "Hello World"}

@router.get('{id}/get_last')
def test():
    return {"msg": "test"}

在中间件中,我试图获取请求路由而不是 URL

def check_for_api_access(self,request: Request):
    request_path = request.scope['path']
    # route_path = request.scope['endpoint']  # This does not exists

    url_list = [
        {'path': route.path,'name': route.name}
        for route in request.app.routes
    ]

我期待的结果是:{id}/get_all 用于第一个请求,{id}/get_last 用于第二个请求。

我能够获取 url_list 中所有路径的列表,但我想要特定 request 的路由路径

此处提供的尝试解决方案:https://github.com/tiangolo/fastapi/issues/486 对我也不起作用

解决方法

虽然您可以非常接近标准框架(即框架没有花哨的改动),但您可能无法完全完成所需的工作。

在中间件中,可以直接访问请求。这样,您就可以检查请求的 url,如 https://fastapi.tiangolo.com/advanced/using-request-directly/?h=request 中所述。此处描述了可访问的属性https://www.starlette.io/requests/


注意由于您只发布了片段,因此很难说出值/变量的来源。

在您的情况下,不起作用的事情很简单。如果您查看我发布的网址,starlette docs 会显示您可以从请求中访问的属性。这正好包含您正在寻找的属性。

基本上,将 request_path = request.scope['path'] 更改为 request_path = request.url.path。如果你有前缀,那么你也会得到它,这就是我说 You may not be able to accomplish exactly what you need,though you can get very close with the standard framework (i.e. no fancy alterations of the framework). 的原因。不过,如果你知道你的前缀,你可以将它从路径中删除(它只是一个字符串)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...