从 Flask 路由中的 URL 获取变量 [英] Get a variable from the URL in a Flask route

查看:36
本文介绍了从 Flask 路由中的 URL 获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a number of URLs that start with landingpage and end with a unique id. I need to be able to get the id from the URL, so that I can pass some data from another system to my Flask app. How can I get this value?

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

推荐答案

这在 快速入门.

您需要一个可变 URL,您可以通过在 URL 中添加 占位符并在视图函数中接受相应的 name 参数来创建它.

You want a variable URL, which you create by adding <name> placeholders in the URL and accepting corresponding name arguments in the view function.

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

更常见的是,URL 的各个部分用 / 分隔.

More typically the parts of a URL are separated with /.

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

使用 url_for 生成页面的 URL.

Use url_for to generate the URLs to the pages.

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

您也可以将值作为查询字符串的一部分传递,并且 从请求中获取,但如果总是需要,最好使用上述变量.

You could also pass the value as part of the query string, and get it from the request, although if it's always required it's better to use the variable like above.

from flask import request

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

# /landingpage?id=A

这篇关于从 Flask 路由中的 URL 获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆