gpt4 book ai didi

python - FastAPI:如何从请求中获取原始 URL 路径?

转载 作者:行者123 更新时间:2023-12-05 08:10:38 26 4
gpt4 key购买 nike

我有一个 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' object has no attribute 'endpoint'

最佳答案

以下解决方案对我来说效果很好使用带有 count 参数的字符串替换仅替换第一次出现的字符串。 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

关于python - FastAPI:如何从请求中获取原始 URL 路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72217828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com