Fastapi:如何从请求中获取原始URL路径?

问题描述 投票:0回答:4

I有一个

GET
方法,其中有请求的参数在路径中:

@router.get('/users/{user_id}')
async def get_user_from_string(user_id: str):
    return User(user_id)

可以从请求中获取基本URL原始路径(即

'/users/{user_id}'
)? 我试图使用以下方式:

path = [route for route in request.scope['router'].routes if route.endpoint == request.scope['endpoint']][0].path

但是它不起作用,我得到:

attributeError:'mount'对象没有属性'端点'

python url-routing fastapi starlette
4个回答
8
投票

如果您需要的是原始路由路径,即,您可以使用以下内容。它的工作方式是首先获取

/users/{user_id}

(通常是一个空字符串),除非您已将

Sub-application(s)
安装到顶级应用程序(例如,
root_path
),因此,因此,您需要将结果与该特定路径app.mount("/subapi", subapi)一起使用,然后将其附加到路由路径上,您可以从
apiroute
对象获得该路径。示例:
/subapi

输出

from fastapi import Request @app.get('/users/{user_id}') def get_user(user_id: str, request: Request): path = request.scope['root_path'] + request.scope['route'].path return path 原始答案

为每个fastapi
documentation

aftapi实际上是在下面的星形,有几层 最上面的工具,您可以直接使用starlette的/users/{user_id}

对象 需要

,您可以使用

Request
对象获取URL路径。例如:

Request

output
(如果接收到

from fastapi import Request @app.get('/users/{user_id}') def get_user(user_id: str, request: Request): return request.url.path
user_id

): 1

    
下面的解决方案对我来说很好
使用字符串替换为

/users/1
参数仅替换第一个事件。 
count

1
投票
request.path_params


我正在努力实施此操作以及使用可用数据的原始路线的方法如下:
def get_raw_path(request):
    path = request.url.path
    for key, val in request.path_params.items():
        path = path.replace(val, F'{{{key}}}',1)
    return path

注意,接受的答案没有返回所要求的内容,因为它返回了服务器所收到的路径。
其他答案中没有涉及安装应用程序。

1
投票

thaving找到了两个不起作用的答案,我将分享我使用的内容。 它并不好,好像路径参数中有共享值,它将无法使用

def get_route_from_request(req: Request):
  root_path = req.scope.get("root_path", "")

  route = scope.get("route")
  if not route:
    return None
  path_format = getattr(route, "path_format", None)
  if path_format:
    return f"{root_path}{path_format}"

  return None

您可以在请求中使用apirout对象属性来获取实际路径

示例:

path = request.url.path for key, val in request.path_params.items(): path = path.replace(val, F'{{{key}}}')

-1
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.