Python 从 Flask 路由中的 URL 获取变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35188540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:07:05  来源:igfitidea点击:

Get a variable from the URL in a Flask route

pythonurlflask

提问by Ben J.

I have a number of URLs that start with landingpageand 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?

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

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

采纳答案by davidism

This is answered in the quickstartof the docs.

这在文档的快速入门中得到了回答。

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

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

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

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

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

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

Use url_forto generate the URLs to the pages.

使用url_for生成的URL的网页。

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.

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

from flask import request

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

# /landingpage?id=A