从Flask路由中的URL获取变量

2024-10-17 08:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多URL以landingpage开头,以唯一id结尾。我需要能够从URL获取id,以便我可以将一些数据从另一个系统传递到我的Flask应用程序。我怎样才能得到这个值

http://localhost/landingpageA
http://localhost/landingpageB
http://localhost/landingpageC

Tags: 数据id应用程序localhosthttpurlflask系统
2条回答

像这样的例子

@app.route('/profile/<username>')
def lihat_profile(username):
    return "welcome to profile page %s" % username

这在文件的quickstart中得到了回答

您需要一个变量URL,可以通过在URL中添加<name>占位符并在view函数中接受相应的name参数来创建该变量URL

@app.route('/landingpage<id>')  # /landingpageA
def landing_page(id):
    ...

更典型的是,URL的各个部分用/分隔

@app.route('/landingpage/<id>')  # /landingpage/A
def landing_page(id):
    ...

使用url_for生成页面的URL

url_for('landing_page', id='A')
# /landingpage/A

您还可以将该值作为查询字符串的一部分传递get it from the request,不过如果总是需要,最好使用上面的变量

from flask import request

@app.route('/landingpage')
def landing_page():
    id = request.args['id']
    ...

# /landingpage?id=A

相关问题 更多 >