首页 > 解决方案 > 如何在Flask中请求最后一段url

问题描述

我觉得答案很简单,但我似乎无法弄清楚。我有一个网址:

http://127.0.0.1:5000/fight_card/fight/5

我试图在我的代码中只使用“5”,因为它是 SQL 表中当前战斗的 ID。到目前为止,我已经尝试过

fight = Fight.query.filter_by(id=request.path).first()

然而,返回:

fight_card/fight/5

有什么方法可以使用“请求”来仅针对 5 个?先感谢您!

标签: flask

解决方案


您应该在路由定义中包含一个变量 , current_fight_id。然后,您可以在视图函数中访问该变量。


@app.route('/fight_card/fight/<current_fight_id>')
def fight_route(current_fight_id):
   print(current_fight_id) # use variable in route

或者,您可以使用您正在使用的方法,但修改返回的字符串。如果你有一个字符串:

endpoint = "fight_card/fight/5" # returned by your current code

您可以通过以下方式访问五个(current_fight_id):

current_fight_id = endpoint.split("/")[-1] # grab the segment after the last "/"

推荐阅读